ios - JSON解析swift,数组在NSURLSession之外没有值

标签 ios arrays json swift uitableview

我正在尝试在 swift 中调用一个 json web 服务,使用以下代码并将其显示在 swift IOS 中的 tableview 中。

/*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 中,

我还想用这个数组来填充表格 View 。 这是示例 json 输出文件

[

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

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

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

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

]

我是swift的新手,请帮忙

最佳答案

想法是使用“回调”。

这里,我为你想要得到的NSArray做了一个:

completion: (dataArray: NSArray)->()

我们创建一个函数来获取数组,并将此回调添加到函数的签名中:

func getDataArray(urlString: String, completion: (dataArray: NSArray)->())

一旦数组准备就绪,我们将使用回调:

completion(dataArray: theNSArray)

完整的函数如下所示:

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()
    }
}

现在我们像这样使用这个函数,不再有异步问题:

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)
}

Swift 3 更新 + 修复和改进。

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 {
            // ...
        }
    }
}

关于ios - JSON解析swift,数组在NSURLSession之外没有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37340967/

相关文章:

ios - UIWebView 无需转到 iOS 的视频播放器即可播放 Html 5 视频

ios - 如何从 iOs 中的 QuickDialog 获取值

ruby-on-rails-3 - 使用 rabl 和一个集合,在添加额外的子节点时遇到问题

javascript - 使用 Javascript 有条件地过滤对象数组

python - 用中值替换 numpy 数组中的零

json - 了解 Json 格式的 openweathermap 结果

python - 如何使用 python 在 JSON 输出上显示所有字符串匹配

ios - Objective-C 随机数

ios - 段错误 11 仅适用于 xcode 10 swift 3

arrays - 将数组拆分为哈希