我尝试在SWIFT代码中调用临时转换器服务但是,我在控制台中得到相同的println“NO”:
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.
}
}
我没有看到错误在哪里,我没有错误的行。我试着理解为什么我不能得到“是”的消息,有人可以帮助我吗?
答案 0 :(得分:0)
连接不是Bool类型,因此您将始终使用connection == true
获得falso。这就像问香蕉是否是苹果一样。明显的答案总是“假”
要检查连接对象是否已经分配,你应该检查它是否为零,所以if应该是if connection != nil
这不能确保你的“呼叫是好的”,就像你在评论中所说的那样。它只会确保连接对象已成功创建,您应该在调用start方法之前检查它。 (并且你真的不需要调用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
}