0

I have function to send asynchronous request of a URL on Swift 1.2, but it doesn't work on 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)
                })
            }
        }

}
}

pls help :)

1 Answers1

0

NSURLConnection was deprecated in iOS 9 which is probably what is giving you trouble. As far as I can make out from what you are trying to do the "new way" would be to initialize a NSURLSession and then a NSURLSessionDataTask to retrieve the data you require. This can be done with a completion handler in much the same way as you have outlined here, or also with delegate methods. You can find out more at the Developer reference page: https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSession_class/ I can send some sample code over if you like. Good luck!

Marcus
  • 2,153
  • 2
  • 13
  • 21