且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将CURL命令转换为Swift

更新时间:2023-02-16 19:54:43

我会说你应该使用Proliphix提供的API。

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

如您所见,它们提供了一个示例,并且您已经设法弄清楚如何通过cURL提供正确的参数,因此现在您只是需要将其转换为Swift。

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.

为此,您需要HTTP网络API,可以使用 NSURLSession 苹果公司提供的API,或者

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.

这些API的网址为 / get / pdp 。然后,您需要告诉他们这是GET还是POST请求。如果API需要任何数据(例如您的情况下的OID参数),则还需要提供该数据,然后设置最终标头。

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.

这里是有关如何使用NSURLSession执行此操作的示例:

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 :-)
}

希望这能使您朝正确的方向前进。现在,您知道要搜索的内容了,您也可以在Google搜索NSURLSession或Alamofire教程。

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.