Sunil Sunil - 2 months ago 8
iOS Question

bind Json with post request

After trying from a whole day and checking many links on stack overflow and few forums I am not able to crack it : I think many

swift
developers finds it very easy but I am not able to crack it please help

I Have a url and a JSON to bind and get the JSON Response

Url to POST: http://myurl/myurl.com.......//

JSON Request:

{
"BookingId": "1501433021",
"ProductType": "0",
"Client": "1",
"OriginAirport": {
"CityCode": "NYC",
"CityName": "New York",
"AirportCode": "NYC",
"AirportName": "New York City All Airports",
"Country": "US",
"Terminal": ""
},
"DestinationAirport": {
"CityCode": "LON",
"CityName": "London",
"AirportCode": "LON",
"AirportName": "London All Airports",
"Country": "GB",
"Terminal": ""
},
"TravelDate": "2016-10-19T05:07:57.865-0400 ",
"ReturnDate": "2016-10-21T05:08:02.832-0400 ",
"SearchDirectFlight": false,
"FlexibleSearch": false,
"TripType": 2,
"Adults": 1,
"Children": 0,
"Infants": 0,
"CabinType": 1,
"SearchReturnFlight": true,
"Airline": "",
"CurrencyCode": "USD",
"SiteId": "LookupFare"
}


MyCode (this code is copied from some where I am just trying to make it work for me) Which obviously not working for me

import UIKit

class SearchFlightsVC: UIViewController{

override func viewDidLoad() {

print("vdfvdfvdf")

// prepare json data
let json = ["BookingId": "1501433021",
"ProductType": "0",
"Client": "1",
"OriginAirport": [
"CityCode": "CLT",
"CityName": "Charlotte",
"AirportCode": "CLT",
"AirportName": "Douglas Intl",
"Country": "US",
"Terminal": ""
],
"DestinationAirport": [
"CityCode": "YTO",
"CityName": "Toronto",
"AirportCode": "YTO",
"AirportName": "Toronto All Airports",
"Country": "CA",
"Terminal": ""
],
"TravelDate": "2016-10-19T05:07:57.865-0400",
"ReturnDate": "2016-10-21T05:08:02.832-0400",
"SearchDirectFlight": false,
"FlexibleSearch": false,
"TripType": 2,
"Adults": 1,
"Children": 0,
"Infants": 0,
"CabinType": 1,
"SearchReturnFlight": true,
"Airline": "",
"CurrencyCode": "USD",
"SiteId": "LookupFare" ]

do {

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


// create post request
let url = NSURL(string: "http://myurl/myurl.com.......//")!
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

print(response)


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)
}
}
}


I already checked

How to create and send the json data to server using swift language

HTTP Request in Swift with POST method

But nothing works for me

ALL HELP IS Appreciated Thanks in Advance !!!

Answer

This is the code I wrote for my app and customized for your request

         func sendRequest(address: String, method: String, body: Dictionary<String, AnyObject>) {
        let url = NSURL(string: address)
        let request = NSMutableURLRequest(URL: url!)
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.HTTPMethod = method

        do {
            request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(body, options: NSJSONWritingOptions.init(rawValue: 2))
        } catch {
            // Error handling
            print("There was an error while Serializing the body object")
            return
        }

        let session = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in

            do {
                if error != nil {
                    print("Error -> \(error)")
                    return
                }

                if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? [NSDictionary] {
                    let result = json
                }

            } catch {
                print("Send request error while Serializing the data object")
                return
            }

        })

        session.resume()

    }

    sendRequest("your.URL.come", method: "POST", body: json)

hope this will help to and one more thing add TransportSecurity to your info.plist or copy line blow and change the "your.URL.come" with your base address

  <key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>your.URL.come</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

hope this will help

Comments