swift |未解决的标识符错误

时间:2017-09-30 00:27:14

标签: swift3

以下是代码:

let task: URLSessionDataTask = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
     // Get the HTTP status code of the request.
        let statusCode = (response as! HTTPURLResponse).statusCode
        if statusCode == 200 {
            // Convert the received JSON data into a dictionary.
            do {
                if let dataDictionary = (try? JSONSerialization.jsonObject(with: data!, options: [JSONSerialization.ReadingOptions.mutableContainers])) as? [String:Any] { let accessToken = dataDictionary["access_token"] as? String }

                UserDefaults.setObject(accessToken, forKey: "LIAccessToken")
                UserDefaults.standard.synchronize()

                DispatchQueue.main.async(execute: { () -> Void in
                    self.dismiss(animated: true, completion: nil)
                    })
            }
            catch {
                print("Could not convert JSON data into a dictionary.")
            }
        }

新代码:(这是来自app coda,无法在最新的swift中编译,https://github.com/appcoda/LinkedInSignInDemo/blob/master/LISignIn/WebViewController.swift

让dataDictionary =尝试NSJSONSerialization.JSONObjectWithData(data!,options:NSJSONReadingOptions.MutableContainers)

                let accessToken = dataDictionary["access_token"] as! String

                NSUserDefaults.standardUserDefaults().setObject(accessToken, forKey: "LIAccessToken")
                NSUserDefaults.standardUserDefaults().synchronize()

                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    self.dismissViewControllerAnimated(true, completion: nil)
                })

1 个答案:

答案 0 :(得分:0)

你必须这样使用:

您在if循环中定义了accessToken。你正在外面访问它。

if let dataDictionary = (try? JSONSerialization.jsonObject(with: data!, options: [JSONSerialization.ReadingOptions.mutableContainers])) as? [String:Any] { 
    let accessToken = dataDictionary["access_token"] as? String 
    UserDefaults.setObject(accessToken, forKey: "LIAccessToken")
}