-2

I'm a newbie to Swift. I'm trying to simply read in a web page and I am getting the error "Initialization of immutable value 'task' was never used; consider replacing it with assignment to '_' or removing it" error on the "let task = " statement. Here's my code (please excuse my debugging statements). What am I doing wrong?

let urlPath = "http://www.stackoverflow.com"
let url = URL(string: urlPath)
let session = URLSession.shared
let task = session.dataTask(with:url!) { (data, response, error) -> Void in
    if (error == nil) {
        print("inside If")
        print(data)
    } else {
        print("inside Else")
        print(error)
    }
    print("after If Else")
}
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
CMan
  • 71
  • 1
  • 7

1 Answers1

1

What you are seeing is actally a warning, the compiler is telling you that you initialized a varaible but never used it. In general you can either replace the variable name with _ or remove the declaration entirely since you are not using it (or just ignore the warning). However in your case you actually need it, after you initialize the data task, you are not actually using it, which is why you aren't seeing any of your print statements being output. To fix this, call task.resume(). Doing this will also remove the warning since you are now actually using that variable.

let urlPath = "http://www.stackoverflow.com"
let url = URL(string: urlPath)
let session = URLSession.shared
let task = session.dataTask(with:url!) { (data, response, error) -> Void in
    if (error == nil) {
        print("inside If")
        print(data)
    } else {
        print("inside Else")
        print(error)
    }
    print("after If Else")
}
task.resume()
Sasang
  • 1,261
  • 9
  • 10
  • 1
    True, will update to be more consistent. But i'll be damned if this trend continues. I like me some semicolons, like a proper language.... – Sasang May 10 '17 at 00:05
  • Thanks Sasang for the explanation. – CMan May 10 '17 at 12:24
  • This got me past my initial problem, then I ran into another issue: **Optional(Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection."** I found this posting which got me past it: [link](http://stackoverflow.com/questions/32631184/the-resource-could-not-be-loaded-because-the-app-transport-security-policy-requi) – CMan May 10 '17 at 13:04