解析Swift词典的中学水平

时间:2017-05-08 17:52:30

标签: swift dictionary request

我有一个来自我的服务器的JSON对象:

let alertController = UIAlertController(title: "Your alert", message: "", preferredStyle: .alert)

let saveAction = UIAlertAction(title: "Save", style: .default, handler: {
    alert -> Void in

    guard let textField = alertController.textFields?[0] as UITextField else { return }
    yourLabel.text = textField.text
})

let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: {
    (action : UIAlertAction!) -> Void in })

alertController.addTextField { (textField : UITextField!) -> Void in
    textField.placeholder = "Whatever"
    //Other textField configurations
}

alertController.addAction(saveAction)
alertController.addAction(cancelAction)

present(alertController, animated: true, completion: nil)

这将以userInfo的形式转换为字典。但是,由于我的令牌未在userinfo中返回,我如何将其解析为类。目前,我的 初始化看起来像硬编码字符串:

LOGIN_SUCCESS with JSON: {
    token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJteS5kb21haW4uY29tIiwic3ViIjoiNTkwOTRkNjRjMmRhN2E3MWI4NTljYTFhIiwiaWF0IjoxNDk0MjY1NTE1LCJleHAiOjE0OTQ4NzAzMTV9.SqsLeToG8-_3CV1Yr4Z4SUIv4-vqGbntGwFLB4i7n-w";
    user =     {
        "__v" = 0;
        "_id" = 59094d64c2da7a71b859ca1a;
        createdAt = "2017-05-03T03:24:20.309Z";
        email = "dylan@msn.com";
        name = Dylan;
        updatedAt = "2017-05-03T03:24:20.309Z";
    };
}

完整请求尝试:

self.loggedInUser.setUser(firstName: "Dylan" as String!,
                          email: "dylan@msn.com"as String!,
                          token: "test" as String!,
                          id: "1"as String!,
                          longitude: "40.0"as String!,
                          latitude: "-70"as String!)

self.loggedInUser.printUser()

}

1 个答案:

答案 0 :(得分:1)

找到以下更正的代码:

if response.response?.statusCode == 200 {
            print("LOGIN_SUCCESS with JSON: \(response.result.value!)")
            if let responseData = response.value as? [String : Any] {
                let token = responseData["token"] as? String
                if let userInfo = responseData as? [String : Any] {
                self.loggedInUser.setUser(firstName: userInfo.["user"]["name"] as! String!,
                                          email: userInfo["email"] as! String!,
                                          token: userInfo["token"] as! String!,
                                          id: "1"as String!,
                                          longitude: "40.0"as String!,
                                          latitude: "-70"as String!)
                self.loggedInUser.printUser()
                return completion(self.loggedInUser, nil)
            }
            }
        }