Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 解析JSON第一次不起作用_Ios_Json_Swift - Fatal编程技术网

Ios 解析JSON第一次不起作用

Ios 解析JSON第一次不起作用,ios,json,swift,Ios,Json,Swift,我在单独的swift类文件上有一个dataTask,用于将一些数据检索到数组中: if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSArray { let resourceIDs = NSMutableArray() var result = NSArray() for i in 0 ..< jsonResult.co

我在单独的swift类文件上有一个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!")
}

当我第一次调用button函数时,如何从我的view controller中获取数组以填充?

设置ResourceID后,您不会更新ViewController。你应该调用一个完成块或其他东西来通知你的VC,或者在最坏的情况下在该属性中添加一个
DidSet
VC.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
函数中,检查闭包中的保留周期。

为什么在Swift中使用
NS[Mutable]数组
NS[Mutable]字典
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!")
}