2016-02-26 60 views
8

我使用FBSDK和Xcode 7.2.1来检索用户配置文件信息并使用SwiftyJson处理和操作json数据。在更改值/删除一些我想要使用JSON数据发送到我的API的发布请求。但是我很快就遇到了非常糟糕的类型问题。Alamorafire + SwiftyJson + FacebookSDK

这是我的代码,以使POST请求:

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 
} 

不幸的是我收到此错误:

Cast from 'JSON' to unrelated type '[String : AnyObject]' always fails

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

Cannot convert value of type 'JSON' to expected argument type '[String : AnyObject]?'

任何帮助表示赞赏。我只想知道,如何将JSON对象转换为String AnyObject?没有失败。或发送JSON对象作为后/ PUT /补丁请求数据与夫特2.

+0

尝试从.URL改变编码以.json –

+0

这不是问题。没有工作.. – artuc

+0

没问题,你可以分享userProfile的数据? –

回答

1
JSON

SwiftyJson定义的自定义类型。尝试在您的案例中使用userProfile.dictionaryObject以获取潜在的快速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 
    } 
} 
+0

感谢您的答案,但是当我这样做时,我无法获得有效的json,所以它会从api中引发错误。这是之前/之后的输出:http://pastebin.com/i1JqgFec – artuc

+0

@artuc是的,因为默认情况下,'userProfile.dictionaryObject'将返回一个可选的'Dictionary'。你必须打开它。 –

+0

感谢@ J.Wang的帮助,不幸的是,当我这样做时,它会返回无效的JSON。在dictionaryObject之前,一切都很好,但是我不能发送JSON类型与alamofire(对于我来说也是可以的,如果有其他库我可以发送它),但是对于这个,dictionaryObject返回错误的JSON,所以我的服务器返回一个错误对我来说。 – artuc