Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alamorafire + SwiftyJson + FacebookSDK

I use FBSDK with Xcode 7.2.1 to retrieve user profile information and use SwiftyJson to handle and manipulate json data. After changing values / removing some i want to make a post request to my api with the JSON data. But i am stucked with the really bad type issues in swift.

This is my code to make a post request:

 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
 }

Unfortunately i receive this error:

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

If i try to send the JSON data directly to API i receive this error:

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

Any help are appreciated. I just want to know, how to convert JSON object to String AnyObject? without failing. Or sending Json object as post / put / patch request data with Swift 2.

like image 873
artuc Avatar asked Feb 26 '16 23:02

artuc


1 Answers

JSON is a custom type defined in SwiftyJson. Try using userProfile.dictionaryObject in your case to get the underlying swift Dictionary.


Unwrap the optional dictionary by this

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
    }
}
like image 134
J.Wang Avatar answered Nov 18 '22 00:11

J.Wang