Daniel Zam Daniel Zam - 5 months ago 211
Swift Question

Swift- Use of unresolved identifier

I have the following Swift code where I am sending a POST request to a webserver and receiving a value back. The error that I receive is on the second to last line saying "Use of unresolved identifier"

func download_request() -> String {
let url:NSURL = NSURL(string: "http://url.com/read.php")!
let session = NSURLSession.sharedSession()

let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

let paramString = "data=name"
request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)

let task = session.downloadTaskWithRequest(request) {

(let location, let response, let error) in

guard let _:NSURL = location, let _:NSURLResponse = response where error == nil else {
print("Error")
return
}

let urlContents = try! NSString(contentsOfURL: location!, encoding: NSUTF8StringEncoding)

guard let _:NSString = urlContents else {
print("Error")
return
}

}

task.resume()
return urlContents
}


How would I fix this error? I think that it means that I cannot use urlContents outside of the let task = session.downloadTaskWithRequest(request) { } but how would I declare the variable so that I can use it outside?

Answer

Try declaring urlContents outside of the session.downloadTaskWithRequest(request) { } block. Like so:

func download_request() -> String? {
    let url:NSURL = NSURL(string: "http://url.com/read.php")!
    let session = NSURLSession.sharedSession()
    var urlContents: NSString?

    let request = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "POST"
    request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

    let paramString = "data=name"
    request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)

    let task = session.downloadTaskWithRequest(request) {

        (let location, let response, let error) in

        guard let _:NSURL = location, let _:NSURLResponse = response  where error == nil else {
            print("Error")
            return
        }

        urlContents = try? NSString(contentsOfURL: location!, encoding: NSUTF8StringEncoding)

        guard let _:NSString = urlContents else {
           print("Error")
           return
        }

     }

    task.resume()
    return (urlContents as! String)
}

Then when you need to use urlContents unwrap it with an if let binding

if let contents = download_request() {
    //Use safely unwrapped contents
}