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?
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.
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!)")
}
Since NSURLConnection.sendAsynchronousRequest
is deprecated in iOS 9. Should use NSURLSession
public func dataTaskWithRequest(request: NSURLRequest, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDataTask
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With