Question: How to solve Xcode error message 'url' instance member cannot be used on type 'view controller'

Question

How to solve Xcode error message 'url' instance member cannot be used on type 'view controller'

Answers 1
Added at 2016-12-22 15:12
Tags
Question

I typed the following swift code in Xcode and it shows error message

'url' instance member cannot be used on type 'view controller'

here's my code-

let url = NSURL(string: "http://www.stackoverflow.com")!

let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in


}
Answers
nr: #1 dodano: 2016-12-22 15:12

Here's the code for Swift 3 and the error message of Xcode 8.2.1 (current version):

let url = URL(string: "http://www.stackoverflow.com")!
var task = URLSession.shared.dataTask(with: url) {
    (data: Data?, response: URLResponse?, error: Error?) in
}

and the error message in line 2 is now:

Cannot use instance member 'url' within property initializer; property initializers run before 'self' is available

This makes it more clear, I think. Creating the task must be done later in a function like viewDidLoad.

This code would work (well, at least it compiles):

var task: URLSessionTask?

override func viewDidLoad() {
    super.viewDidLoad()

    if let url = URL(string: "http://www.stackoverflow.com") {
        task = URLSession.shared.dataTask(with: url) {
            (data: Data?, response: URLResponse?, error: Error?) in

            // Handle response and errors here
        }
    }

    // Do any additional setup after loading the view.
}
Source Show
◀ Wstecz