2017-07-14 4 views
-1

初めて動作しません:解析JSONは配列にいくつかのデータを取得するために、私は別の迅速なクラスファイルにdataTaskを持って

if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSArray { 

    let resourceIDs = NSMutableArray() 
    var result = NSArray() 

    for i in 0 ..< jsonResult.count { 

     let jsonElement : NSDictionary = jsonResult[i] as! NSDictionary 

     let resourceID = jsonElement["ResourceID"]! 

     resourceIDs.add(resourceID) 
    } 

    result = resourceIDs 
    print(result) // data is stored 
    VC.resourceIDs = result //pass the object's NSArray to the ViewController's NSArray 
} 
else { 

    print("Could not parse JSON!") 
} 

私が初めての私のボタンの機能を呼び出そう、私のViewControllerのNSArray resourceIDsは何も受信しません。ボタンの機能をもう一度呼び出すと、配列にデータが入力されます。

@IBAction func btnCheckAvailability(_ sender: UIButton) { 

    showOverlayOnTask(message: "Please wait...") 

    let dateFormatter = DateFormatter() 
    let timeFormatter = DateFormatter() 
    dateFormatter.dateFormat = "yyyy-MM-dd" 
    timeFormatter.dateFormat = "HH:mm:ss" 
    let date = dateFormatter.string(from: startDate) 
    let time = timeFormatter.string(from: startDate) 
    CheckAvailableModel().checkAvailable(resourceType: resourceType!, startDate: date, startTime: time, VC: self) 

    if (resourceIDs.count > 0) { 

     DispatchQueue.main.async { 

      self.dismiss(animated: false, completion: { action in 

       print(self.resourceIDs) 
      }) 
     } 
    } 
    else { 

     DispatchQueue.main.async { 

      self.dismiss(animated: false, completion: { action in 

       print("No available resources") 
      }) 
     } 
    } 
} 

ボタン機能を初めて呼び出すと、ビューコントローラーから配列を取り込む方法を教えてください。

+0

Swiftネイティブ配列や辞書の代わりにSwiftで 'NS [Mutable] Array'と' NS [Mutable] Dictionary'を使っているのはなぜですか? – rmaddy

答えて

0

リソースIDを設定すると、ViewControllerが更新されません。完了ブロックなどを呼び出してVCに知らせるか、最悪の場合はDidSetをそのプロパティに追加する必要があります。

一方、機能を最適化することができます。

if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [[String: Any]] { 
    let resourceIDs: [String] = [] 

    for jsonElement in jsonResult { 
     let resourceID = jsonElement["ResourceID"]! 
     resourceIDs.append(resourceID) 
    } 
    VC.resourceIDs = resourceIDs 
} 
else { 
    print("Could not parse JSON!") 
} 

また、あなたのbtnCheckAvailability機能で閉鎖に保持サイクルをご確認ください。

関連する問題