【问题标题】:sendSynchronousRequest is deprecated in ios 9 [duplicate]ios 9 中不推荐使用 sendSynchronousRequest [重复]
【发布时间】:2015-10-05 14:48:32
【问题描述】:

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

【问题讨论】:

  • 使用 NSURLSession 代替 NSURLConnection
  • 如果有某种方法可以使用一些关键词搜索互联网。 bfy.tw/286i
  • 我并不愚蠢,我看到了其他问题,但我不明白那里选择的答案哈哈

标签: ios swift swift2


【解决方案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 响应响应时将调用它。

【讨论】:

  • 如何将响应值分配给 urlData(NSData) ?
  • 我的代码会像这样检查响应 if ( urlData != nil ) { let res = response as! NSHTTPURL响应!; if (res.statusCode >= 200 && res.statusCode
  • @RULE101 我更新了我的代码,告诉你如何获取 url 和响应代码。在我的代码中,我已经打印了它们,但你可以做任何你想做的检查。如果你还需要什么,请告诉我
  • 好的,当我运行代码时,我在这一行得到了这个让 jsonData:NSDictionary = (try!NSJSONSerialization.JSONObjectWithData(response, options:NSJSONReadingOptions.MutableContainers)) 作为! NSDictionary 错误:无法将 NSURLresponse 的值类型转换为 NSData
  • 响应是一个JSON顺便说一句
最近更新 更多