gpt4 book ai didi

ios - JSON 解析数据未被调用? swift

转载 作者:可可西里 更新时间:2023-11-01 01:39:02 25 4
gpt4 key购买 nike

我已经从 API 解析了我的数据,但是当我尝试从解析的 NSDictionary 数据中设置一些值时,没有调用 println 语句。它发生在带有“用户”键的字典中,我尝试在其中设置学生的名字和姓氏。

func getUserData(hostViewController: UIViewController ) {
if self.userID == nil{
println("User ID is nil")
}
else {
var key = self.userID
let urlString = UdacityClient.Constants.BaseURLSecure + "/users" + "/\(key)"
println(urlString)
let url = NSURL(string: urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
let request = NSMutableURLRequest(URL: url!)


let task = session.dataTaskWithRequest(request) {data, response, error in
if error != nil {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
println(error)
let alertController = UIAlertController(title: "Oh no", message: "Error in User Data", preferredStyle: UIAlertControllerStyle.Alert)

let cancelAction = UIAlertAction(title: "Retry", style: UIAlertActionStyle.Default, handler: { (alert) -> Void in
hostViewController.dismissViewControllerAnimated(true, completion: nil)
})
alertController.addAction(cancelAction)

hostViewController.presentViewController(alertController, animated: true, completion: nil)
})

println("Error in User Data")

} else {
let newData = data.subdataWithRange(NSMakeRange(5, data.length - 5))
var parsingError: NSError? = nil
let parsedResult = NSJSONSerialization.JSONObjectWithData(newData, options: NSJSONReadingOptions.AllowFragments, error: &parsingError) as! NSDictionary


if let userDictionary = parsedResult["user"] as? [String: AnyObject] {
if let firstName = userDictionary["first_name"] as? String {
self.firstName = firstName
println("This is not printing ")
println(firstName)
}
}

if let userDictionary = parsedResult["user"] as? [String: AnyObject] {
if let lastName = userDictionary["last_name"] as? String {
self.lastName = lastName
println("This is not printing also")
println(lastName)
}
}

if let err = parsingError {
dispatch_async(dispatch_get_main_queue(),{ () -> Void in
println(err)
let alertController = UIAlertController(title: "Oh no", message: "Error in Parsing User Data from Udacity", preferredStyle: UIAlertControllerStyle.Alert)

let cancelAction = UIAlertAction(title: "Retry", style: UIAlertActionStyle.Default, handler: { (alert) -> Void in
hostViewController.dismissViewControllerAnimated(true, completion: nil)
})
alertController.addAction(cancelAction)

hostViewController.presentViewController(alertController, animated: true, completion: nil)
})

}


}
}


task.resume()
}
}

我的请求 URL:

https://www.udacity.com/api/users/Optional("3778758647")

我的 ResponseKeys 结构:

struct JSONResponseKeys {
//getSessionID
static let Status = "status"
static let Account = "account"
static let Key = "key"
static let Session = "session"
static let ID = "id"

//getUserData
static let User = "user"
static let FirstName = "first_name"
static let LastName = "last_name"


}

当我在下面的客户端中调用学生的名字和姓氏时,在展开可选值时发生 fatal error :

UdacityClient.sharedInstance().firstName!) and      UdacityClient.sharedInstance().lastName!

JSON 解析结果控制台日志:

 {
error = "Parameter 'user_key' key contains unescaped special character '\"': 'Optional(\"3778758647\")'";
parameter = "user_key";
status = 400;
}

最佳答案

我看起来你的主要错误来自于 userID 是一个需要解包的可选值这一事实。这就是你看到的原因

https://www.udacity.com/api/users/Optional("3778758647")代替https://www.udacity.com/api/users/3778758647 和您的服务器错误说的是同一件事。

试试这个基本大纲,而不是:

if self.userID == nil {
...
}

你可以使用 guard 语句提前返回,像这样:

guard let userID = self.userID as? String else { return }

这样做的好处是还可以展开您的值(value),摆脱 "Optional()"

另一种方法是使用:

if let userID = self.userID as? String {
...
}

关于ios - JSON 解析数据未被调用? swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32420778/

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