ios - 使用 AFNetworking 时如何从 Anyobject 获取值

标签 ios swift afnetworking

我在我的新个人项目中使用了 AFNetworking 和 swift。当我向服务器发送登录请求时,服务器将返回一个带有 json 的响应,而 AFNetworking 会将 json 转换为 Anyobject。但是当我尝试使用 anyobject 时遇到了一些问题。

登录成功时的json数据如下:

{"code":0,"data":{"id":"1"}}

这是我的登录码:

manager.POST("\(SERVER_HOST)User/login", parameters: params, success: { (operation:AFHTTPRequestOperation!, response:AnyObject!) -> Void in
      var code = response.objectForKey("code") as Int

      if code == 0{
         var data = response.objectForKey("data") as NSDictionary
         var id = data.objectForKey("id")?.integerValue

         self.performSegueWithIdentifier("loginSucceed", sender: self)
      }

})

所以我的问题是:代码可以工作,但是当我使用

var id = data.objectForKey("id") as Int

就像我获取代码值的方式一样,应用程序崩溃了,id 得到了一个 nil 值。为什么?

另一个问题是:使用更复杂的 json 字符串获取值的正确方法是什么。 任何帮助将不胜感激

最佳答案

当你这样做时你的代码崩溃了:

var id = data.objectForKey("id") as Int

因为 "id" 对应的值是 String "1" 而不是 Int 1。如果类型错误,强制转换 as 会崩溃。使用条件转换 as? 并将其与可选绑定(bind)结合起来会更安全:

if let code = response["code"] as? Int {
    // if we get here we know "code" is a valid key in the response dictionary
    // and we know we got the type right.  "code" is now an unwrapped `Int` and
    // is ready to use.

    if code == 0 {
        if let data = response["data"] as? NSDictionary {
            // if we get here, we know "data" is a valid key in the response
            // dictionary and we know it holds an NSDictionary.  If it were
            // some other type like `Int` we wouldn't have entered this block

            if let id = data["id"] as? String {
                // if we get here, we know "id" is a valid key, and its type
                // is String.

                // Use "toInt()" to convert the value to an `Int` and use the
                // default value of "0" if the conversion fails for some reason
                let idval = id.toInt() ?? 0
                println("idval = \(idval)")
            }
        }
    }
}

关于ios - 使用 AFNetworking 时如何从 Anyobject 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26007797/

相关文章:

ios - 使用什么来移动 UIView self.frame 或 self.transform 属性?

objective-c - 在 NSMutableArray 和 Sqlite 中存储 CGPoints

ios - 将图像设置在背景中心,按钮周围有内部空间

swift - 在 AFNetworking swift 的 header 响应中获取 token 的值

ios - 从 ASIHTTPRequest 转换为 AFNetworking 的最佳实践?

ios - 从容器 View 的 View Controller 中,如何访问包含容器的 View Controller ?

ios - Swift CNCopySupportedInterfaces 无效

swift - 删除 UIContainerView 中 UITableView 之前的空白 - Xcode 6.4,Swift

swift - FIRAuth 文件与 FirebaseUI 不兼容 : use of undeclared identifier 'FIRAuthErrorUserInfoUpdatedCredentialKey'

ios - AFNetworking-iOS在PHP打印时获取JSON