Swift版本2.0 有一个小地方需要注意在成功的Return我使用了一个第三方的XML转字典的库~访问默认传回来的是NSdata,第三方库叫做XMLDictionary,需要的可以在github上搜索一下~
/**使用Post方式请求WebCommonService数据,闭包中含有操作UI的方法必须刷新主线程UI
:param: PostUrl WebCommonService地址
:param: SOAPAction SOAPAction响应地址
:param: SoapBody SoapBody结构*/
func SDXmlrequestPost(PostUrl:String,SOAPAction:String,SoapBody:String,Success:(results:NSDictionary) -> Void,Failure:(error:NSError?)->Void){ /
/创建SOAP消息 let SoapMsg = "\(SoapBody)"
// print(SoapMsg)
//创建一个URL请求 let Url = NSURL(string: PostUrl)
//创建请求对象 let request = NSMutableURLRequest(URL: Url!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 15)
//添加请求头 request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue("\(SoapMsg.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))", forHTTPHeaderField: "Content-Length")
request.addValue(SOAPAction, forHTTPHeaderField: "SOAPAction") request.HTTPMethod = "POST"
// 将SOAP消息加到请求中 request.HTTPBody = SoapMsg.dataUsingEncoding(NSUTF8StringEncoding)
let seesion = NSURLSession.sharedSession()
let dataTask = seesion.dataTaskWithRequest(request) { (data:NSData?, req:NSURLResponse?, error:NSError?) -> Void in
if error == nil{
//把XML数据转字典
return Success(results: NSDictionary(XMLData: data!))
}else{
return Failure(error: error) }
}
//启动任务 dataTask.resume()
}