Tsutomu Okumura Tsutomu Okumura - 1 month ago 16
JSON Question

Swift post json to Rails

I can't post json value to Rails from swift.


My Rails code is


def create

@movie = Movie.new
@movie.caption = movie_params["caption"]
@movie.language = movie_params["language"]
@movie.movie_file = movie_params["movie_file"]
@movie.save
end


def movie_params
params.require(:movie).permit(:caption, :language, :movie_file)
end


curl is working fine.

curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST -d '{"movie":{"caption":"hoge","language":"TH","movie_file":"2016-10-16T14-30-30"}}' http://localhost:3000/movies.json


But how can I post json from swift.

xcode environment is

AFNetworking 3.0

SwiftyJSON 2.3.2


My swift code is


let dict: [String: AnyObject] = [
"movie": [
"caption": "hoge",
"language":"",
"movie_file":""
]
]

var json: String = ""
do {
// Dict -> JSON
let jsonData = try NSJSONSerialization.dataWithJSONObject(dict, options: []) //(*)options??

json = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String
} catch {
print("Error!: \(error)")
}

let strData = json.dataUsingEncoding(NSUTF8StringEncoding)


let manager: AFHTTPSessionManager = AFHTTPSessionManager()
manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Content-Type")
manager.responseSerializer.acceptableContentTypes = NSSet(object: "application/json") as? Set<String>

let server_request = String(format: "%@/%@", self.server_url, request)

let escapedRequest = server_request.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())


// here "jsonData" is the dictionary encoded in JSON data

manager.POST(escapedRequest!, parameters: strData, progress: nil, success: { (operation, dataFromNetworking) -> Void in

let jsonObj = JSON(dataFromNetworking!)
callback(jsonObj)

}, failure:{ (operation, error) -> Void in

})


When I post this, I got error in Rails output

Started POST "/movies.json" for 127.0.0.1 at 2016-10-20 10:40:52 +0700
Error occurred while parsing request parameters.
Contents: =%3C7b226d6f%2076696522%203a7b226c%20616e6775%2061676522%203a22222c%2022636170%2074696f6e%20223a2268%206f676522%202c226d6f%207669655f%2066696c65%20223a2222%207d7d%3E

ActionDispatch::ParamsParser::ParseError (822: unexpected token at '=%3C7b226d6f%2076696522%203a7b226c%20616e6775%2061676522%203a22222c%2022636170%2074696f6e%20223a2268%206f676522%202c226d6f%207669655f%2066696c65%20223a2222%207d7d%3E'):
actionpack (4.2.5) lib/action_dispatch/middleware/params_parser.rb:53:in `rescue in parse_formatted_parameters'
actionpack (4.2.5) lib/action_dispatch/middleware/params_parser.rb:32:in `parse_formatted_parameters'


I'm really appreciated you help me. I'm struggling whole days.
Thanks in advance!

-TOM

Answer

Try this,

do {

    let jsonData = try NSJSONSerialization.dataWithJSONObject(dict, options: .PrettyPrinted)

    // create post request
    let url = NSURL(string: "https://...your_host.com/movies.json")!
    let request = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "POST"

    // insert json data to the request
    request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
    request.HTTPBody = jsonData


    let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
        if error != nil{
            print("Error -> \(error)")
            return
        }

        do {
            let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]

            print("Result -> \(result)")

        } catch {
            print("Error -> \(error)")
        }
    }

    task.resume()
    return task



} catch {
    print(error)
}

Ref: How to make HTTP Post request with JSON body in Swift

Comments