2016-07-29 8 views
0

ネットワークコールからいくつかの(json)データを取得しようとしていますが、ネットワークデータを待つより良い方法があるのでしょうか?ちょうど空のループよりも。私は、実行時に無限ループになったのObjective-Cで似た何かをしようとして覚えて値を返す前にネットワークコールが完了するのを待つ

func sendAPIRequest(endpoint:String) -> JSON? 
{ 
    var json = JSON("") 
    let request = NSMutableURLRequest(URL: NSURL(string: "https://host.com/".stringByAppendingString(endpoint))!) 
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in 
     guard error == nil && data != nil else {               // check for fundamental networking error 
      print("error=\(error)") 
      return 
     } 
     if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {   // check for http errors 
      print("statusCode should be 200, but is \(httpStatus.statusCode)") 
     } 
     json = JSON(data: data!) 
    } 
    task.resume() 
    while (json == "") { 
     // Wait 
    } 
    return json 
} 

は、ここに私のコードです。

+0

は、コールバックを使うのか?要求が完了したら、このコールバックを呼び出してそこから処理を進めます。 –

答えて

3

非同期操作から値を返す場合は、完了ハンドラが必要です。 dataTaskWithRequestは非同期処理です。この操作を行います。

func sendAPIRequest(endpoint:String, complete: (JSON) ->()) 
{ 
    var json = JSON("") 
    let request = NSMutableURLRequest(URL: NSURL(string: "https://host.com/".stringByAppendingString(endpoint))!) 
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in 
     guard error == nil && data != nil else {               // check for fundamental networking error 
      print("error=\(error)") 
      return 
     } 
     if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {   // check for http errors 
      print("statusCode should be 200, but is \(httpStatus.statusCode)") 
json = JSON(data: data!) 
complete(json) 
     } 

    } 
    task.resume() 

} 

をそしてそのようにそれを呼び出す:

sendAPIRequest(<your endpoint string>) { theJSON in 
//Use the Json value how u want 
} 
関連する問題