JSON 解析迅速,数组在 NSURLSession 之外没有任何值 [英] JSON parsing swift, array has no value outside NSURLSession

查看:36
本文介绍了JSON 解析迅速,数组在 NSURLSession 之外没有任何值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 swift 中调用一个 json webservice,使用以下代码并将其显示在 swift IOS 的 tableview 中.

/*声明为全局*/var IdDEc = [String]()//全局声明的字符串数组//在viewdidload里面让 url = NSURL(string: "http://192.1.2.3/PhpProject1/getFullJson.php")让 task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in让 json1 = NSString(data: data!, encoding: NSUTF8StringEncoding)print("json string is = ",json1)//我在这里得到响应让数据 = json1!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)做 {让 json = 尝试 NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as!数组用于 json 中的 arrayData {让 notId = arrayData["ID"] 作为!细绳self.IdDEc.append(notId)}print(" id = ",IdDEc)//这里我正在获取值} catch let error as NSError {print("加载失败:\(error.localizedDescription)")}print(" id out count = ",self.IdDEc.count)//这里也是}print(" id out count = ",self.IdDEc.count)//不在这里任务.resume()

我将数组 IdDEc 声明为全局,该数组的作用域仍然仅驻留在 NSURLSession 中,

我也想用这个数组来填充 tableview.这是示例 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"}]

我是一个新手,请帮忙

解决方案

这个想法是使用回调".

这里,我为您想要获取的 NSArray 创建了一个:

补全:(dataArray: NSArray)->()

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

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

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

completion(dataArray: theNSArray)

完整的函数如下所示:

func getDataArray(urlString: String, completion: (dataArray: NSArray)->()) {如果让 url = NSURL(string: urlString) {NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in如果错误 == 零 {如果让数据 = 数据,json1 = NSString(data: data, encoding: NSUTF8StringEncoding),数据1 = json1.dataUsingEncoding(NSUTF8StringEncoding,allowLossyConversion:false){做 {让 json = 尝试 NSJSONSerialization.JSONObjectWithData(data1, options: [])如果让 jsonArray = json 为?NSArray {完成(数据数组:jsonArray)}} catch let error as NSError {打印(错误.本地化描述)}} 别的 {打印(错误:没有数据")}} 别的 {打印(错误!.localizedDescription)}}.恢复()}}

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

getDataArray("http://192.1.2.3/PhpProject1/getFullJson.php") { (dataArray) in用于 dataArray { 中的 dataDictionaryif let notId = dataDictionary["ID"] as?细绳 {self.IdDEc.append(notId)}}print("id out count = ", self.IdDEc.count)}

<小时>

Swift 3 更新 + 修复和改进.

func getContent(from url: String, completion: @escaping ([[String: Any]])->()) {如果让 url = URL(string: url) {URLSession.shared.dataTask(with: url) { (data, response, error) in如果错误 == 零 {如果让数据 = 数据 {做 {让 json = 尝试 JSONSerialization.jsonObject(with: data, options: [])如果让内容 = json 为?[[String: Any]] {//字典数组完成(内容)}} 抓住 {//解码 JSON 时出错打印(错误.本地化描述)}} 别的 {打印(错误:没有数据")}} 别的 {//网络相关错误打印(错误!.localizedDescription)}}.恢复()}}getContent(from: "http://192.1.2.3/PhpProject1/getFullJson.php") { (result) in//'result' 是赋予 'completion' 的,是一个字典数组为 dataDictionary 结果 {if let notId = dataDictionary["ID"] as?细绳 {//...}}}

I am trying to call a json webservice in swift, With the following code and display it in tableview in swift IOS.

/*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()

i declared the array IdDEc as global, still the scope of that array resides inside NSURLSession only,

Also i want to use this array to populate tableview. Here is the sample json output file

[

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

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

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

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

]

I am a newbee in swift please help

解决方案

The idea is to use a "callback".

Here, I've made one for the NSArray you want to get:

completion: (dataArray: NSArray)->()

We create a function to get the array, and we add this callback to the function's signature:

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

and as soon as the array is ready we'll use the callback:

completion(dataArray: theNSArray)

Here's how the complete function could look like:

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

Now we use this function like this, no more asynchronous issues:

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 update + fixes and improvements.

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

这篇关于JSON 解析迅速,数组在 NSURLSession 之外没有任何值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆