【发布时间】:2017-12-20 18:08:57
【问题描述】:
我刚开始使用 swift4 为 ios 编写应用程序,我遇到了 2 个问题,我正在调用一个肥皂网络服务,它成功了, 我可以在输出中打印结果(xml格式的字符串),我想用这个结果更新一个文本字段的文本,因为这个任务在后台运行,我把下面的代码放在了completionHandler的闭包中:
@IBOutlet weak var txt1: UITextField!
func httpGet(request: URLRequest)-> String{
let soapReqXML = "some code..."
let is_URL: String = "http://xxx.x.x.12/soapservice.asmx"
let url = URL.init(string: is_URL)
let my_Request = NSMutableURLRequest(url: url!)
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: self, delegateQueue:OperationQueue.main)
my_Request.httpMethod = "POST"
my_Request.httpBody = soapReqXML.data(using: String.Encoding.utf8, allowLossyConversion: false)
my_Request.addValue("host add...", forHTTPHeaderField: "Host")
my_Request.addValue("text/xml;charset =utf-8", forHTTPHeaderField: "Content-Type")
my_Request.addValue(String(soapReqXML.count), forHTTPHeaderField: "Content-Length")
my_Request.addValue("http://mservice.my.xx/SNA...", forHTTPHeaderField: "SOAPAction")
var responseData : Data = Data()
var _re : String = "000"
let task = session.dataTask(with: my_Request as URLRequest, completionHandler: {data, response, error -> Void in
if error == nil {
responseData = data!
_re = self.stringFromXML(data:responseData); // calling stringFromXML to convert data into string
print("the result is :"+_re) // working here, I can see the good result in the output
//execute from the main thread to update txt1
DispatchQueue.main.async(execute:{
self.txt1.text = re // first problem, the error is :Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
self.txt1.text = "text" // I even change into "text", same error happened here
})
}
})
task.resume()
return _re // second problem, the return is always 000
}
我的第一个问题是:如果我在 ipad 模拟器中调用该函数,在调试中,它是这样写的:txt1=(UITextField!) nil, 第二个问题是,返回总是000(初始值)
有人可以帮我检查一下吗?提前谢谢!
【问题讨论】:
标签: swift web-services asynchronous soap