ios - 将 Json 与 post 请求绑定(bind)

标签 ios json swift post

经过一整天的尝试并检查了堆栈溢出和几个论坛上的许多链接后,我无法破解它:我认为许多 swift 开发人员发现它非常容易,但我无法破解请帮忙

我有一个 url 和一个 JSON 来绑定(bind)并获取 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

但对我来说没有任何作用

感谢所有帮助,提前致谢!!!

最佳答案

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

         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>

希望这会有所帮助

关于ios - 将 Json 与 post 请求绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39657745/

相关文章:

arrays - 向下转换多个协议(protocol) Array<protocol<P1, P2>> 到 Array<P1>

ios - Swift Socket.io连接后立即发送的事件未执行

ios - 字符串中指定的颜色变化。 swift iOS

ios - 使用默认数据集创建 CoreData 模型

python - 在 Python 中存储字符串的好方法是什么?

ios - 如何在 iOS 中找到目标的 Action 函数

html - 像google/facebook中的设备身份验证

javascript - 可用性日历 jQuery(?)

java - 我如何从java中的xquery获取json?

ios - 我目前正在检查 UIAlertController 是否存在以确定正在使用的操作系统版本。有没有更有效的方法来做到这一点?