2016-05-20 9 views
1

json webserviceをswiftで呼び出しようとしています。次のコードを使用して、swift IOSのtableviewに表示しています。JSONの構文解析、NSURLSessionの外側に配列がありません

/*declared as global*/ var IdDEc = [String]() // string array declared globally 

//inside viewdidload 

let url = NSURL(string: "http://192.1.2.3/PhpProject1/getFullJson.php") 

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

let json1 = NSString(data: data!, encoding: NSUTF8StringEncoding) 

print("json string is = ",json1) // i am getting response here 

let data = json1!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) 

    do { 

        let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSArray 

            for arrayData in json { 

                let notId = arrayData["ID"] as! String 

                self.IdDEc.append(notId) 
            } 

            print(" id = ",IdDEc) //here i am getting values 

        } catch let error as NSError { 

            print("Failed to load: \(error.localizedDescription)") 
        } 

        print(" id  out count = ",self.IdDEc.count) //here also 
    } 

    print(" id  out count = ",self.IdDEc.count) // not here 

    task.resume() 

私はグローバルとして配列IdDEcを宣言し、まだその配列の範囲が唯一NSURLSession内に存在する、

はまた、私はテーブルビューを移入するために、この配列を使用します。ここ は、サンプルのJSON出力ファイルは、私が迅速でnewbee午前

[ 

{"ID":"123" , "USER":"philip","AGE":"23"}, 

{"ID":"344","USER":"taylor","AGE":"29"}, 

{"ID":"5464","USER":"baker","AGE":"45"}, 

{"ID":"456","USER":"Catherine","AGE":"34"} 

] 

ある

+1

データが準備されていません。非同期要求を実行していることに注目してください。 – Desdenova

+0

@Desdenovaああですか?それで、データをキャッチするのを助けてください。私は素早く新しいです。そのため、ポストはasynctaskのデータをキャッチする方法を実行します。 – Mukund

+0

Swiftにはjavaのようなポスト実行メソッドはありません。範囲内では、データにアクセスできます。そこから移動してください。 – Desdenova

答えて

3

アイデアは、「コールバック」を使用することです助けてください。ここで

、私はあなたが取得したいNSArrayのための1つを作った:

completion: (dataArray: NSArray)->() 

我々は配列を取得する関数を作成し、我々は関数のシグネチャにこのコールバックを追加します。

func getDataArray(urlString: String, completion: (dataArray: NSArray)->()) 
すぐに、アレイは、我々はコールバックを使用します準備ができているよう

と:

completion(dataArray: theNSArray) 

はここでどのように完了します

getDataArray("http://192.1.2.3/PhpProject1/getFullJson.php") { (dataArray) in 
    for dataDictionary in dataArray { 
     if let notId = dataDictionary["ID"] as? String { 
      self.IdDEc.append(notId) 
     } 
    } 
    print("id out count = ", self.IdDEc.count) 
} 

スウィフト3更新+修正と改良:今、私たちは、このように、それ以上の非同期の問題を、この機能を使用しない

func getDataArray(urlString: String, completion: (dataArray: NSArray)->()) { 
    if let url = NSURL(string: urlString) { 
     NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in 
      if error == nil { 
       if let data = data, 
        json1 = NSString(data: data, encoding: NSUTF8StringEncoding), 
        data1 = json1.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) { 
        do { 
         let json = try NSJSONSerialization.JSONObjectWithData(data1, options: []) 
         if let jsonArray = json as? NSArray { 
          completion(dataArray: jsonArray) 
         } 
        } catch let error as NSError { 
         print(error.localizedDescription) 
        } 
       } else { 
        print("Error: no data") 
       } 
      } else { 
       print(error!.localizedDescription) 
      } 
     }.resume() 
    } 
} 

:機能は次のようになります。

func getContent(from url: String, completion: @escaping ([[String: Any]])->()) { 
    if let url = URL(string: url) { 
     URLSession.shared.dataTask(with: url) { (data, response, error) in 
      if error == nil { 
       if let data = data { 
        do { 
         let json = try JSONSerialization.jsonObject(with: data, options: []) 
         if let content = json as? [[String: Any]] { // array of dictionaries 
          completion(content) 
         } 
        } catch { 
         // error while decoding JSON 
         print(error.localizedDescription) 
        } 
       } else { 
        print("Error: no data") 
       } 
      } else { 
       // network-related error 
       print(error!.localizedDescription) 
      } 
     }.resume() 
    } 
} 

getContent(from: "http://192.1.2.3/PhpProject1/getFullJson.php") { (result) in 
    // 'result' is what was given to 'completion', an array of dictionaries 
    for dataDictionary in result { 
     if let notId = dataDictionary["ID"] as? String { 
      // ... 
     } 
    } 
} 
関連する問題