我不知道我需要一个可选类型意味着什么。我试图做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)
}
答案 0 :(得分:0)
使用此行,使用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
}