Cannot call "sendAsynchronousRequest" in Swift 2 using argument list

I am currently rewriting portions of my Swift 1.2 code for compatibility with Swift 2.0. Actually, I can’t understand what changes have been made to sendAsynchronousRequest - currently all my requests are failing

NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in}) 

Cannot call 'sendAsynchronousRequest' using argument list of type '(NSURLRequest, queue: NSOperationQueue, completeHandler: (NSURLResponse !, NSData !, NSError!) β†’ Void)'

Do you have any idea what is wrong?

+6
source share
4 answers

With Swift 1.2 and Xcode 6.3, the sendAsynchronousRequest:queue:completionHandler: signature

 class func sendAsynchronousRequest(request: NSURLRequest, queue: NSOperationQueue!, completionHandler handler: (NSURLResponse!, NSData!, NSError!) -> Void) 

With Swift 2 and Xcode 7, however, the signature of sendAsynchronousRequest:queue:completionHandler: has changed now:

 // Note the non optionals, optionals and implicitly unwrapped optionals differences class func sendAsynchronousRequest(request: NSURLRequest, queue: NSOperationQueue, completionHandler handler: (NSURLResponse?, NSData?, NSError?) -> Void) 

As a result, switching to Swift 2 and Xcode 7 beta, you will have to change the implementation of the completionHandler parameter and make sure that your queue parameter is not optional.

+6
source

The problem seems to be related to your implicit deployed options in the completion block. Just make it optional and it should work fine,

 NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response: NSURLResponse?, data: NSData?, error: NSError?) in let string = NSString(data: data!, encoding: NSISOLatin1StringEncoding) print("Response \(string!)") } 
+4
source

Since NSURLConnection.sendAsynchronousRequest deprecated in iOS 9. Must use NSURLSession public func dataTaskWithRequest(request: NSURLRequest, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDataTask

+2
source

swift 3

  let url:URL? = URL(string:location) if url == nil { print("malformed url : \(location)") } NSURLConnection.sendAsynchronousRequest(URLRequest(url:url!), queue: OperationQueue.main) { (response: URLResponse?, data: Data?, error: Error?) -> Void in } 
0
source

Source: https://habr.com/ru/post/988898/


All Articles