Rolando
Rolando

Reputation: 62596

NSData is not a subtype of NSData?

I am geting the error:

NSData is not a subtype of NSData from my code below, what am I doing wrong?

let urlPath = "myurl"
var url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(url, completionHandler: {data, response, error -> Void in
    if error {
        println(error)
    } else {
        println(data)
    }
})

task.resume()

Upvotes: 1

Views: 265

Answers (2)

Lance
Lance

Reputation: 9012

The error you're getting is very misleading. The real issue is that NSURL(string:) is a failable initializer, so it returns an optional. But dataTaskWithRequest doesn't take an NSURL? it takes an NSURL

Theres another error in your code, error isn't a boolean so you need to compare it to nil. Here's the code that compiles:

let urlPath = "myurl"
if let url = NSURL(string: urlPath) {
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(url, completionHandler: { (data, response, error) in
        if (error != nil) {
            println(error)
        } else {
            println(data)
        }
    })
}

Upvotes: 0

Darren
Darren

Reputation: 25619

The actual error message is 'NSData!' is not a subtype of 'NSData' (notice the ! after NSData)

NSURL(string:) is a failable initializer, which is new in Swift 1.1 (Xcode 6.1). Failable initializers return an optional that will be nil upon failure.

You must check for failure before you can use the url:

let urlPath = "myurl"
if let url = NSURL(string: urlPath) {
    let session = NSURLSession.sharedSession()
    let request = NSURLRequest(URL: url)
    let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        if error != nil {
            println(error)
        } else {
            println(data)
        }
    })
    task.resume()
}

Upvotes: 1

Related Questions