-2
     func getJSON(a:String,i:Int) -> [String]{

    let upper = "http://api.themoviedb.org/3/search/movie?query="
    let restpart = "&api_key=5565bb94f87424577ef39f24d901ff06"
    let newurl = upper + a + restpart
    let url = NSURL(string: newurl)
    let request = NSURLRequest(URL: url!)
    var thetitle: String = "noerror"
    var desc: String = "noerror"
    var id: String = String(404)
    let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
    let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in

        if error == nil{
            let swiftyJSON = JSON(data: data!)
            thetitle = swiftyJSON["results"][0]["title"].stringValue
            desc = swiftyJSON["results"][0]["overview"].stringValue
            id = (swiftyJSON["results"][0]["id"].stringValue)

            //print(thetitle)
        }
        else{
            thetitle = "error"
            desc = "error"
            id = "0";
            print("there was an error")
        }
    }

    var newFriend = [thetitle,desc,id]
    print(thetitle)
    task.resume()
    return newFriend
}

I want to return newFriend array but it seems the value is always the default value. How can I fix this?

I recognize the return type of task is void, does it mean I can't make changes to other code inside that block?

SurvivalMachine
  • 7,158
  • 13
  • 53
  • 74
Qian Wu
  • 18
  • 5
  • 1
    Just search for "return value from dataTaskWithRequest" or "return value from asynchronous request". This has been asked and answered frequently. – Martin R Jul 14 '16 at 19:00

1 Answers1

0

Networking takes time. Running code doesn't. session.dataTaskWithRequest is asynchronous. theTitle and desc and id are set asynchronously — long after newFriend is returned. Do you see? You can't make time run backwards.

matt
  • 447,615
  • 74
  • 748
  • 977
  • so you mean newFriend is returned ahead of making change to task? Isn't that suppose to proceed in order. And how should i fix this? – Qian Wu Jul 14 '16 at 18:36
  • Yes I do mean that, no it isn't supposed to "proceed in order", and you cannot "fix" it because nothing is wrong. Search on "asynchronous". If you want to do something after the `dataTaskWithRequest` function you must do it _in_ the `dataTaskWithRequest` function. – matt Jul 14 '16 at 18:43