2017-07-14 91 views
-1

我有一个dataTask在一个单独的迅速类文件检索某些数据到一个数组工作:解析JSON并不首次

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中使用NS [Mutable] Array和NS [Mutable] Dictionary来代替Swift本地数组和字典? – rmaddy

回答

0

设置了resourceID之后,你并没有更新ViewController。你应该打电话给一个完成区块或其他东西来通知你的VC,或者在最坏的情况下为该属性添加DidSetVC.resourceIDs = result

另一方面,您可以优化您的功能。

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功能检查保留周期中关闭。