斯威夫特2&异步请求的JSON函数

时间:2016-09-08 21:15:23

标签: json asynchronous swift2

我有函数在Swift 1.2上发送URL的异步请求,但它在Swift 2上不起作用。

func getpost(method:String,bodyt:String,url:String,completion: (res: AnyObject?)->Void){
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
let urlString = url
let url:NSURL! = NSURL(string: urlString)
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = method
let postString = bodyt
if method.uppercaseString == "POST"{
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
}
let mainQueue = NSOperationQueue.mainQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
    {(response, data, error) in
        if let httpResponse = response as? NSHTTPURLResponse {
            let statusCode = httpResponse.statusCode
            if (error == nil) && (statusCode == 200){
                let resultdata: AnyObject?  = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil)
                dispatch_async(dispatch_get_main_queue(), {
                    completion(res: resultdata)
                })
            }
        }

}
}

请帮助:)

1 个答案:

答案 0 :(得分:0)

在iOS 9中不推荐使用NSURLConnection,这可能会给您带来麻烦。据我所知,“新方法”是初始化NSURLSession,然后是NSURLSessionDataTask来检索所需的数据。这可以使用完成处理程序完成,其方式与您在此处概述的方式非常相似,也可以使用委托方法完成。您可以在开发人员参考页面上找到更多信息:https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSession_class/ 如果你愿意,我可以发送一些示例代码。祝你好运!