使用post请求绑定Json

时间:2016-09-23 09:48:37

标签: ios json swift post

在尝试了一整天并检查堆栈溢出和少数论坛上的许多链接之后我无法解决它:我认为很多swift开发人员发现它很容易但我无法破解它请帮助

我有一个url和一个JSON来绑定并获得JSON响应

要发布的网址:http://myurl/myurl.com.......//

JSON请求:

{
"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(这段代码是从我试图让它起作用的地方复制而来的)这显然不适合我

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

我已经检查了

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

HTTP Request in Swift with POST method

但是没有什么对我有用

提前感谢所有帮助!!!

1 个答案:

答案 0 :(得分:0)

这是我为我的应用编写的代码,并根据您的请求进行了自定义

         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)

希望这会有所帮助,还有一件事就是将TransportSecurity添加到您的info.plist或复制行,并使用您的基地更改“your.URL.come”

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

希望这会有所帮助