在ios 9中不推荐使用sendSynchronousRequest

时间:2015-10-05 14:48:32

标签: ios swift swift2

Xcode表示sendSynchronousRequest现已弃用。

我应该如何更换它?

let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
let postLength:NSString = String( postData.length )
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")

var response: NSURLResponse?
var urlData: NSData?
do {
    urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
} catch _ as NSError {
    urlData = nil
} catch {
    fatalError()
}

1 个答案:

答案 0 :(得分:1)

这是一个有效的例子, 你应该使用NSURLSession和Request。

     func testPost(sender: UIButton) {
            let session = NSURLSession.sharedSession()
            let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8080/iOSServer/ios/helloworld/swiftCalculator")!)
            request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
            request.HTTPMethod = "POST"
            let d = "4"
            let data = "x=4&y=\(d)"
            request.HTTPBody = data.dataUsingEncoding(NSASCIIStringEncoding)
            let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
                if let error = error {
                    print(error)
                }
                if let data = data{
                    print("data =\(data)")
                }
                if let response = response {
                print("url = \(response.URL!)")
                print("response = \(response)")
                let httpResponse = response as! NSHTTPURLResponse
                print("response code = \(httpResponse.statusCode)")

                //if you response is json do the following
                  do{
                    let resultJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())
                    let arrayJSON = resultJSON as! NSArray
                    for value in arrayJSON{
                        let dicValue = value as! NSDictionary
                        for (key, value) in dicValue {
                            print("key = \(key)")
                            print("value = \(value)")
                        }
                    }

                }catch _{
                    print("Received not-well-formatted JSON")
                }
            }
            })
            task.resume()
        }

请注意,没有必要使用该请求。您可以使用URL创建数据任务,但我添加了请求,因为在您的代码中,您已在请求中设置了一些标头。

请注意使用completionHandler,当您的服务器通过http响应进行响应时将调用该文件。

相关问题