gpt4 book ai didi

ios - 无法在 Swift 中执行 NSURLSession.sharedSession().dataTaskWithURL

转载 作者:行者123 更新时间:2023-11-28 16:13:54 25 4
gpt4 key购买 nike

我有一段代码可以从 php 返回的 Json 中获取员工数据,如下所示:

[{"id":"1","email":"KK","password":"KKK","firstName":"KKK","lastName":"KK","photo":null,"phone":"22","mobile":"2","position":"SS","adminstrator_id":"1","department_id":"1"}]

我试过的代码:

func getEmpById (id:String) {
emp = employee()

let myUrl = NSURL(string:"http://localhost/On%20Call%20App/scripts/getEmployee.php?id=\(id)")

let session = NSURLSession.sharedSession()

let task = session.dataTaskWithURL(myUrl!, completionHandler: {
(data, response, error) -> Void in

do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! [[String: AnyObject]]
let dic = json[0]


if let id = dic["id"] , firstName = dic["firstName"] ,lastName = dic["lastName"], mobile = dic["mobile"],phone = dic["phone"],email=dic["email"],pos=dic["position"]{



self.emp.setId(id as! String )

self.emp.setFirstName(firstName as! String)

self.emp.setLastName(lastName as! String)

self.emp.setPhone(phone as! String)

self.emp.setMobile(mobile as! String)

self.emp.setEmail(email as! String)

self.emp.setPosition(pos as! String)



}


} catch {
print(error)

}

})
task.resume()


}

这一行的问题 let task = session.dataTaskWithURL(myUrl!, completionHandler:{ 当应用程序到达这一行时,它将直接转到 task.resume() 不打印任何错误

对完成这项工作有什么帮助吗?

最佳答案

您的响应是Array 类型而不是Dictionary

 let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSArray
let dic = json[0] as! NSDictionary
print(dic.objectForKey("email"))

如果像这样使用 Swift 数组就更好了。

 let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! [[String: AnyObject]]
let dic = json[0]
print(dic["email"])

关于ios - 无法在 Swift 中执行 NSURLSession.sharedSession().dataTaskWithURL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39291231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com