ios - 任务恢复它无法正常运行 swift 3

标签 ios json swift3

我在解析 json 文件时突然遇到 task.resum 问题,下面是我的代码:

let loadURL = "https:// ....."
var people = [Person]()

func getPersonData() {
let request = URLRequest(url: URL(string: loadURL)!)
let urlSession = URLSession.shared
let task = urlSession.dataTask(with: request, completionHandler: { 
(data, response, error) -> Void in
    if let error = error {
        print(error)
        return
    }
    // Parse JSON data
    if let data = data {
        self.people = self.parseJsonData(data)
        OperationQueue.main.addOperation{() -> Void in
            self.tableView.reloadData()
        }
    }
})
task.resume()
}

func parseJsonData(_ data: Data) -> [Person] {
var people = [Person]()

do {
    let jsonResult = try JSONSerialization.jsonObject(with: data, 
options: JSONSerialization.ReadingOptions.mutableContainers) as? 
NSDictionary

    // Parse JSON data
    let jsonPeople = jsonResult?["people"] as! [AnyObject]
    for jsonPerson in jsonPeople {
        let person = Person()
        person.name = jsonPerson["name"] as! String
        person.id = jsonPerson["id"] as! String

        //ERROR//: "unexpectedly found nil when unwrapping optional..."
        let jsonChildren = jsonResult?["children"] as! [AnyObject]
        for jsonChild in jsonChildren {
            let child = Child()
            child.name = jsonEntrance["name"] as! String
            child.age = jsonEntrance["age"] as! Int

            person.children.append(child)
        }

        people.append(person)
    }
} catch {
    print(error)
}
return people
}

我的问题出在这一行:

task.resume() 

调试后,当程序运行到上面一行时,应该回到这段代码:

if let error = error {
    print(error)
    return
}
// Parse JSON data
if let data = data {
    self.people = self.parseJsonData(data)
    OperationQueue.main.addOperation{() -> Void in
        self.tableView.reloadData()
    }

但是,它只是停在此处并且不起作用,只是让应用程序继续工作,但任务不会恢复。

我第一次尝试它是工作的,但后来突然停止了任何帮助吗?感谢高级

最佳答案

请尝试这段代码,它消除了一些不一致。

首先是两个模型类:

class Person {
    let name, id : String
    var children = [Child]()

    init(name: String, id: String) {
        self.name = name
        self.id = id
    }
}

class Child {
    let name : String
    let age : Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

然后是获取和解析 JSON 的代码,我添加了调试消息

let loadURL = "https:// ....."
var people = [Person]()

func getPersonData() {
    let url = URL(string: loadURL)!
    let task = URLSession.shared.dataTask(with: url) { [unowned self] (data, response, error) in
        if let error = error {
            print(error)
            return
        }
        // Parse JSON data
        if let data = data {
            self.people = self.parseJson(from: data)
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
    }
    task.resume()
}

func parseJson(from data: Data) -> [Person] {
    var people = [Person]()

    do {
        if let jsonResult = try JSONSerialization.jsonObject(with: data) as? [String:Any] {

            // Parse JSON data
            if let jsonPeople = jsonResult["people"] as? [[String:Any]] {
                for jsonPerson in jsonPeople {
                    let person = Person(name: jsonPerson["name"] as! String, id: jsonPerson["id"] as! String)

                    if let jsonChildren = jsonPerson["children"] as? [[String:Any]] {
                        for jsonChild in jsonChildren {
                            let child = Child(name: jsonChild["name"] as! String, age: jsonChild["age"] as! Int)
                            person.children.append(child)
                        }
                        people.append(person)
                    }  else {
                        print("The value for key `children` is not an array or the key `children` does not exist")
                    }
                }
            } else {
                print("The value for key `people` is not an array or the key `people` does not exist")
            }
        } else {
            print("JSON root object is not a dictionary")
        }
    } catch {
        print(error)
    }
    return people
}

关于ios - 任务恢复它无法正常运行 swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44712781/

相关文章:

ios - 按钮状态信息

swift3 - NSKeyedArchiver 在 Swift 3 ( XCode 8) 中不起作用

swift - 二元运算符 '===' 不能应用于类型 'Any?' 和 'UIBarButtonItem!' 的操作数

php - 空白(无)条目在 swift 4 中使用 alamofire 请求插入数据库。请解决它

ios - PHImageManager requestImageForAsset 有时会为 iCloud 照片返回 nil

ios - 如何下载并保存音频文件,然后快速播放?

javascript - 如何在发布请求的键的变量内发送值

javascript - 从 api 调用映射时检索嵌套 JSON 对象

ios - UIViewRepresentable 自动大小 - 将 UIKit UIView 大小传递给 SwiftUI

python - 如何解析txt中保存的suds对象?