在服务器swift上发布json格式的数据


Post json formatted data on server swift

我是json和swift的新手我想在服务器上发送json格式的数据和标头这是代码

    "Destination":{"ContactPerson":"Garry Jackson","Address":{"PostCode":"4104","StreetAddress":"Bay View","Suburb":"BAY VIEW","BuildingName":"15 Le Quesne Rd","City":"NAPIER","CountryCode":"NZ"},"PhoneNumber":"027 3356871","Email":"jacko.bv@xtra.co.nz","Name":"Garry Jackson"} 

    let parameters = [
        "Packages" : ["Length" : Length, "Type" : "", "Kg" : Weight, "Height" : Height, "Width" : Width, "Name" : SkuName],
        "issignaturerequired" : true,
        "Outputs":["LABEL_PNG_100X175"],
        "DeliveryReference":86882,
        "Destination":["ContactPerson":self.CustomerFirstname,
                       "Address":["PostCode":self.PostalCode,"StreetAddress":self.Address1,"Suburb":self.City,"BuildingName":"ABC","City":self.City,"CountryCode":"AU"],
                       "PhoneNumber":9998406081,"Email":self.CustomerEmail,"Name":self.CustomerFirstname],
        "PrintToPrinter":true,
        "SendTrackingEmail":"",
        "Commodities":[["UnitKg":1.0000,"Currency":"NZD","Country":"NZ","Units":1,"Description":"Drums Drum Accessories Drum Bags","UnitValue":44.0],["UnitKg":1.0000,"Currency":"NZD","Country":"NZ","Units":1,"Description":"Drums Drum Accessories Drum Bags","UnitValue":44.0]],
        "DeliveryInstructions":"None"
    ]
    let headers = [
        "Content-Type" : "application/json",
        "Access_Key":"Key"
    ]
    Alamofire.request(.POST, "http://api.omniparcel.com/labels/printcheapestcourier", headers: headers, parameters:  parameters).responseJSON {
        response in
        print(response)
        let json = JSON(response.data!) //SwiftyJSON
    }

如何在swift 中发布此数据

您可以使用Alamofire处理HTTPRequest和SwiftyJSON来解析返回的json。或者使用NSURLSession并在swift中反序列化JSON。(您可以在S.O.中搜索一些示例)

    let parameters = [
        "Packages": [
            "length": myLengthVariable,
            "type": "kg"
           //add parameters here
        ]
    ]
    let headers = [
    "Content-Type: application/json"
    //add addition headers here
    ]
    Alamofire.request(.GET, "http://api.omniparcel.com/labels/printcheapestcourier", headers: headers, parameters:  parameters).responseJSON {
 response in
           let json = JSON(response.data) //SwiftyJSON
         //Do whatever you want with the json here
    }

您可以使用Alamofire来实现这一点。https://github.com/Alamofire/Alamofire

 var parameters : [String : AnyObject] = [
        "PackageA" : [["Length" : length, "Type" : type, "Kg" : kg, "Height" : height, "Width" : width, "Name" : name]],
        "issignaturerequired" : "true",
        //Put all your other JSON properties here
    ]
Alamofire.request(.POST, "http://api.omniparcel.com/labels/printcheapestcourier", parameters: parameters, encoding: .JSON)
        .responseJSON { response in
            if let JSON = response.result.value {
                print(JSON);
            }
    }