How to convert CURL command to Swift

10.8k views Asked by At

I am learning to write my first IOS app that will query some basic OIDs from a Proliphix IP Network Thermostat. Proliphix supports several methods such as Curl; PHP and API GET & SET. Out of these methods, what would be the easiest in Swift?

Can someone tell me how to convert one of the the following methods for Swift?

Here are examples of these from the Proliphix API that can be found on a google search.


Curl

Get curl –u hostname:password –-data OID1.1= http://192.168.1.100:8100/get

Set curl –u hostname:password --data OID1.10.5=120 --data submit=Submit http://192.168.1.100:8100/pdp


API GET

The URL used is /get. An API GET request is a list of OIDs where their value is not specified. A properly formatted request should provide the Content-Length header. . The entry is the encoded basic authentication word (See RFC 2617 -HTTP Authentication: Basic and Digest Access Authentication).

Request

POST /get HTTP/1.1
  Authorization: Basic <credentials>
  Content-Type: application/x-www-form-urlencoded
  User-Agent: Jakarta Commons-HttpClient/2.0.2
  Host: 192.168.111.114:8214
  Content-Length: 92
  OID1.10.9=&OID1.2=&OID1.1=&OID1.4=&OID1.8=&OID2.7.1=&

Response

HTTP/1.1 200 OK
  Cache-control: no-cache
  Server: Ubicom/1.1
  Content-Length: 166

[email protected]&OID1.2=SW Dev 114&OID1.1=therm_rev_2 0.1.40&OID1.4=192.168.111.114&OID1.8=00:11:49:00:00:58&OID2.7.1=NT100


API SET

The URL used is /pdp . An API SET is similar to the API GET for the request message, except that the desired value is provided at the equals sign. The response is formatted differently. The entry is the encoded basic authentication word (See RFC 2617 -HTTP Authentication: Basic and Digest Access Authentication). The last item in the request must be “submit=Submit”. Do not include an ‘&’ after the "submit=Submit".

Request

 POST /pdp HTTP/1.1
  Authorization: Basic <credentials>
  Content-Type: application/x-www-form-urlencoded
  User-Agent: Jakarta Commons-HttpClient/2.0.2
  Host: 192.168.111.114:8214
  Content-Length: 193

Response

HTTP/1.1 200 OK
  Cache-control: no-cache
  Server: Ubicom/1.1
  Content-Length: 308

PHP

PHP is a web-server specific scripting language, akin to mod_perl. It integrates well into Apache and offer many web-specific libraries as part of the base system.

Get

$oids = array('OID1.4'=>'', // commonIpAddr
              'OID1.10.5'=>'',
              ‘submit’=>’Submit’); // commonCallhomeInterval
$url = “http://192.168.1.100:8100/get”;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPGET, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$myHeader = array("Content-Type: application/x-www-form-urlencoded" ); curl_setopt($ch, CURLOPT_HTTPHEADER, $myHeader);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($oids)); $response = curl_exec($ch);
curl_close($ch);
$oids = array();
parse_str($response, $oids); // converts '.' to underscore
$localip = $oids['OID1_4'];
$interval = $oids['OID1_10_5']; // in minutes
1

There are 1 answers

0
pbodsk On BEST ANSWER

I would say that you should use the API that Proliphix is providing.

As you can see, they provide an example, and you've already managed to figure out how to provide the correct parameters through cURL so now you "just" need to convert this to Swift.

For this you need a HTTP networking API, you could use either the NSURLSession API provided by Apple, or perhaps Alamofire, just to mention a pair.

These API's take an URL which would be /get or /pdp in your case. Then you need to tell them wether this is a GET or a POST request. If the API needs any data (like the OID parameters in your case), you'll need to provide that as well and then you need to set up eventual headers.

Then you send your request and wait for an answer, which you then react to.

Here is an example on how to do this with NSURLSession:

if let url = NSURL(string: "http://httpbin.org/post"){
    let request = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "POST" //Or GET if that's what you need
    request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")  //This is where you add your HTTP headers like Content-Type, Accept and so on
    let params = ["OID1.2" : "SW+Dev+114", "OID1.4" : "192.168.111.114"] as Dictionary<String, String> //this is where you add your parameters

    let httpData = NSKeyedArchiver.archivedDataWithRootObject(params) //you need to convert you parameters to NSData or to JSON data if the service accepts this, you might want to search for a solution on how to do this...hopefully this will get you in the right direction :-)
    request.HTTPBody = httpData
    let session = NSURLSession.sharedSession()
    session.dataTaskWithRequest(request, completionHandler: { (returnData, response, error) -> Void in
        var strData = NSString(data: returnData, encoding: NSUTF8StringEncoding)
        println("\(strData)")
    }).resume() //Remember this one or nothing will happen :-)
}

Hope this gets you in the right direction. You could also do a Google search for NSURLSession or Alamofire tutorial, now that you know what to search for.