2016-09-04 70 views
1

嗨,我要創建我的要求的身體迅速迅速contsruct與XML請求主體的請求

一個自定義的請求我有問題。

這是我的身體的xml:

<ItemTrackingDetailsRequest xmlns="http://singpost.com/paw/ns"> 
<ItemTrackingNumbers> 
<TrackingNumber>SMT0000000628</TrackingNumber> 
</ItemTrackingNumbers> 
</ItemTrackingDetailsRequest> 

如何將其轉換爲字符串,然後將數據請求?

我有嘗試

let params = "<ItemTrackingDetailsRequest> 
     <ItemTrackingNumbers> 
     <TrackingNumber>\(trackingNumber.uppercaseString)</TrackingNumber> 
     </ItemTrackingNumbers> 
     </ItemTrackingDetailsRequest>" 

     let xmlRequest = NSMutableURLRequest(URL: NSURL(string: url)!) 
     xmlRequest.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) 
     xmlRequest.HTTPMethod = "POST" 
     xmlRequest.addValue("application/xml", forHTTPHeaderField: "Content-Type") 

但因爲我構建體字符串錯誤的PARAMS有錯誤。任何方式從上面的XML構造字符串?任何幫助非常感謝。謝謝

回答

3

斯威夫特不支持多行字符串文字,我還沒有看到任何提案在管道中。如果你作出這樣的要求很多,最好是包裹在構建XML爲你構造你的要求:

struct ItemTrackingRequest { 
    var trackingNumbers: [String] 

    init(trackingNumbers: String...) { 
     self.trackingNumbers = trackingNumbers 
    } 

    func xmlString() -> String { 
     var xml = "<?xml version=\"1.0\"?>" 
     xml += "<ItemTrackingDetailsRequest xmlns=\"http://singpost.com/paw/ns\">" 
     xml += "<ItemTrackingNumbers>" 

     for number in self.trackingNumbers { 
      xml += "<TrackingNumber>\(number)</TrackingNumber>" 
     } 

     xml += "</ItemTrackingNumbers>" 
     xml += "</ItemTrackingDetailsRequest>" 

     return xml 
    } 
} 

let params = ItemTrackingRequest(trackingNumbers: "SMT0000000628").xmlString() 

如果您要求變得複雜(如複雜多了),使用核心數據建模爲此請求並生成XML。

+0

謝謝你只是想出我在我的字符串構造這是錯字錯誤的一些空間。正確的應該是let params =「 \(trackingNumber.uppercaseString)「 –

+0

可以幫我看看這個問題。仍然struglling http://stackoverflow.com/questions/39318514/swift-alamofire-send-xml-request-and-receive-xml-response –