【问题标题】:Alamorafire + SwiftyJson + FacebookSDKAlamorafire + SwiftyJson + FacebookSDK
【发布时间】:2016-06-10 09:02:09
【问题描述】:

我使用 FBSDK 和 Xcode 7.2.1 来检索用户配置文件信息并使用 SwiftyJson 来处理和操作 json 数据。更改值/删除一些值后,我想使用 JSON 数据向我的 api 发出发布请求。但是我在 swift 中遇到了非常糟糕的类型问题。

这是我发出帖子请求的代码:

 let headers = [
      "Content-Type": "application/json"
 ]
 let userProfile = userProfile as? [String : AnyObject]
 Alamofire.request(.POST, "http://localhost:8888/api/profile", parameters: userProfile, headers: headers, encoding:ParameterEncoding.URL) .response { request, response, data, error in
      print(userProfile) //This prints nil
      print(response) //This prints api error for expecting data
 }

不幸的是,我收到了这个错误:

从“JSON”转换为不相关类型“[String : AnyObject]”总是失败

如果我尝试将 JSON 数据直接发送到 API,我会收到此错误:

无法将“JSON”类型的值转换为预期的参数类型“[String : AnyObject]?”

感谢任何帮助。我只想知道,如何将 JSON 对象转换为 String AnyObject?没有失败。或者使用 Swift 2 发送 Json 对象作为 post/put/patch 请求数据。

【问题讨论】:

  • 尝试将编码从 .URL 更改为 .JSON
  • 这不是问题。没用..
  • 没问题可以分享userProfile的数据吗?

标签: xcode swift facebook-ios-sdk


【解决方案1】:

JSONSwiftyJson 中定义的自定义类型。尝试在您的情况下使用 userProfile.dictionaryObject 以获取底层 swift Dictionary


用这个解开可选字典

if let userProfile = userProfile.dictionaryObject {
    Alamofire.request(.POST, "http://localhost:8888/api/profile", parameters: userProfile, headers: headers, encoding:ParameterEncoding.URL) .response { request, response, data, error in
          print(userProfile) //This prints nil
          print(response) //This prints api error for expecting data
    }
}

【讨论】:

  • 感谢您的回答,但是当我这样做时,我无法获得有效的 json,因此它会从 api 抛出错误。这是之前/之后的输出:pastebin.com/i1JqgFec
  • @artuc 是的,因为默认情况下,userProfile.dictionaryObject 将返回一个可选的Dictionary。你必须打开它。
  • 感谢@J.Wang 的帮助,不幸的是,当我这样做时,它返回一个无效的 JSON。在dictionaryObject 之前,一切看起来都很棒,但我无法使用alamofire 发送JSON 类型(如果有任何其他库可以发送它,我也可以),但是有了这个,dictionaryObject 返回错误的JSON,所以我的服务器返回错误对我来说。
  • @artuc 如果你可以在Alamofire.request 之前print(userProfile) 并显示结果,那就太好了。
  • @artuc 这是一个快速的Dictionary。把它交给Alamofire.request 就可以了。它会在发送到您的服务器之前将其转换为有效的 JSON。一定有其他原因导致错误?你能仔细检查一下吗?
猜你喜欢
  • 2015-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-21
  • 2015-01-07
相关资源
最近更新 更多