我尝试用SWIFT代码调用临时转换器服务,但是在控制台“ NO”中得到相同的println:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var is_SoapMessage = "<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body><CelsiusToFahrenheit xmlns='http://www.w3schools.com/webservices/'><Celsius>0</Celsius></CelsiusToFahrenheit></soap:Body></soap:Envelope>"
var is_URL: String = "http://www.w3schools.com/webservices/CelsiusToFahrenheit"
var lobj_Request = NSMutableURLRequest(URL: NSURL(string: is_URL)!)
var session = NSURLSession.sharedSession()
var err: NSError?
/*
lobj_Request.HTTPMethod = "POST"
lobj_Request.HTTPBody = is_SoapMessage.dataUsingEncoding(NSUTF8StringEncoding)
lobj_Request.addValue("testest.it", forHTTPHeaderField: "Host")
lobj_Request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
lobj_Request.addValue(String(count(is_SoapMessage)), forHTTPHeaderField: "Content-Length")
lobj_Request.addValue("http://www.w3schools.com/webservices/CelsiusToFahrenheit", forHTTPHeaderField: "SOAPAction")
*/
var msgLength = String(count(is_SoapMessage))
lobj_Request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
lobj_Request.addValue(msgLength, forHTTPHeaderField: "Content-Length")
lobj_Request.HTTPMethod = "POST"
lobj_Request.HTTPBody = is_SoapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) // or false
/*
var task = session.dataTaskWithRequest(lobj_Request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
if error != nil
{
println("Error: " + error.description)
}
else
{
println("OKAY")
}
})
task.resume()
*/
var connection = NSURLConnection(request: lobj_Request, delegate: self, startImmediately: true)
connection!.start()
if (connection == true) {
var mutableData : Void = NSMutableData.initialize()
println("OKAY")
}
else
{
println("NO")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
我看不到错误在哪里,我没有错误行。我试图理解为什么我无法收到“是”消息,有人可以帮助我吗?
最佳答案
连接不是Bool类型,因此您总是会因connection == true
而失败。就像问香蕉是否是苹果一样。显而易见的答案永远是“假”
要检查连接对象是否已分配,您应该检查它是否不是nil,因此if应该为if connection != nil
,这不能确保您像在评论中所说的那样“通话很好”。它将仅确保已成功创建连接对象,并且应在对其调用start方法之前对其进行检查。 (并且您实际上不需要调用start方法,因为您将start立即参数设置为true)
if let connection = NSURLConnection(request: lobj_Request, delegate: self, startImmediately: true) {
connection.start() //You don't need it because you set the startImmediately param to true
//whatever you want to do the connection
}
关于ios - 在SWIFT中调用SOAP服务,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32141286/