我不知道我需要一个可选类型意味着什么。我尝试执行 Do/catch,但似乎仍然不起作用。
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as! NSDictionary
if let parseJSON = json {
let userId = parseJSON["userId"] as? String
if (userId != nil) {
NSUserDefaults.standardUserDefaults().setObject(parseJSON["userFirstName"], forKey: "userFirstName")
NSUserDefaults.standardUserDefaults().setObject(parseJSON["userLastName"], forKey: "userLastName")
NSUserDefaults.standardUserDefaults().setObject(parseJSON["userId"], forKey: "userId")
NSUserDefaults.standardUserDefaults().synchronize()
// take user to a protected page
/*
let mainPage = self.storyboard?.instantiateViewControllerWithIdentifier("MainPageViewController") as! MainPageViewController
let mainPageNav = UINavigationController(rootViewController: mainPage)
let appDelegate = UIApplication.sharedApplication().delegate
appDelegate?.window??.rootViewController = mainPageNav
*/
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.buildNavigationDrawer()
} else {
// display an alert message
let userMessage = parseJSON["message"] as? String
let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:nil)
myAlert.addAction(okAction);
self.presentViewController(myAlert, animated: true, completion: nil)
}
}
} catch {
print(error)
}
最佳答案
在这一行中,使用 as!
:
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as! NSDictionary
将 NSJSONSerialization 的结果强制转换为 NSDictionary。
因此生成的 json
不是可选的:您不必使用 if let
解开它。
去掉if let parseJSON = json { }
部分,直接使用json
:
let userId = json["userId"] as? String
等等
或者,如果您想将结果保留为可选,您可以使用 as?
:
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as? NSDictionary {
let userId = json["userId"] as? String
// etc
}
关于ios - 条件绑定(bind)的初始化程序必须具有可选类型,而不是 'NSDictionary',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33059486/