0
votes

I'm trying to create a NSURLSession task based on a tutorial I found online (https://www.raywenderlich.com/85528/user-accounts-ios-ruby-rails-swift#next_section) and I am getting the following error:

Cannot convert value of type '(NSData!, NSURLResponse!, NSError!) -> ()' to expected argument type '(NSData?, NSURLResponse?, NSError?) -> Void

at this block of code:

let task = session.dataTaskWithRequest(request) { (data: NSData!, response: NSURLResponse!, error: NSError!) in

The function where the issue belongs to can be found here

func sendRequest(request: NSURLRequest, completion:(NSData!, NSError!) -> Void) -> () {
// Create a NSURLSession task
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data: NSData!, response: NSURLResponse!, error: NSError!) in
  if error != nil {
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
      completion(data, error)
    })

    return
  }

  dispatch_async(dispatch_get_main_queue(), { () -> Void in
    if let httpResponse = response as? NSHTTPURLResponse {
      if httpResponse.statusCode == 200 {
        completion(data, nil)
      } else {
        var jsonerror:NSError?
        if let errorDict = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error:&jsonerror) as? NSDictionary {
          let responseError : NSError = NSError(domain: "HTTPHelperError", code: httpResponse.statusCode, userInfo: errorDict as? [NSObject : AnyObject])
          completion(data, responseError)
        }
      }
    }
  })
}

The full code block can be found here (https://codeshare.io/uJPcX) at line 68.

1
try change data: NSData!, response: NSURLResponse!, error: NSError! to data: NSData?, response: NSURLResponse?, error: NSError?Fonix
That did the trick! Thank you @Fonixnoobdev
no problem :), you should look up how optional variables work to fully understand the difference between ! and ? in swift, also using any of those parameters later on will probably require a ! after them (and some null checks)Fonix

1 Answers

0
votes

Change

data:NSData!, response: NSURLResponse!, error: NSError!

to

data: NSData?, response: NSURLResponse?, error: NSError?

when using data or response etc further down you may have to write is as data! to unwrap the variable, but be careful because if the variable is nil it will crash, so you must check that it is not nil first