Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot invoke 'sendAsynchronousRequest' in Swift 2 with an argument list

Tags:

swift

swift2

I'm currently rewriting parts of my Swift 1.2 code for compatibility with Swift 2.0. Actually I cannot figure out what changes are made to "sendAsynchronousRequest" - currently all my requests fail

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

Cannot invoke 'sendAsynchronousRequest' with an argument list of type '(NSURLRequest, queue: NSOperationQueue, completionHandler: (NSURLResponse!, NSData!, NSError!) -> Void)'

Do you have any Idea what is wrong?

like image 279
Daniel K. Avatar asked Jun 11 '15 07:06

Daniel K.


Video Answer


3 Answers

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

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

With Swift 2 and Xcode 7 beta, however, the signature of sendAsynchronousRequest:queue:completionHandler: has changed and is 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 consequence, turning to Swift 2 and Xcode 7 beta, you will have to change your completionHandler parameter implementation and ensure that your queue parameter is a non optional.

like image 168
Imanou Petit Avatar answered Nov 27 '22 18:11

Imanou Petit


It seems like the problem is with your implicit unwrapped optionals 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!)")
}
like image 36
Sandeep Avatar answered Nov 27 '22 17:11

Sandeep


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

like image 43
Jake Lin Avatar answered Nov 27 '22 18:11

Jake Lin