我想使用SOAP API,但我遇到了问题。
我的委托方法未被调用,URL变量显示无法读取NSURL类型的数据。
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, NSURLConnectionDelegate, XMLParserDelegate {
var mutableData:NSMutableData = NSMutableData.init()
var currentElementName:NSString = ""
@IBOutlet var txtCelsius : UITextField!
@IBOutlet var txtFahrenheit : UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let celcius = "24"
let soapMessage = "<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:xsi='https://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='https://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body><CelsiusToFahrenheit xmlns='https://www.w3schools.com/xml/'><Celsius>\(String(describing: celcius))</Celsius></CelsiusToFahrenheit></soap:Body></soap:Envelope>"
let urlString = "https://www.w3schools.com/xml/tempconvert.asmx"
print(urlString)
if let url = NSURL(string: urlString)
{
print(url)
let theRequest = NSMutableURLRequest(url: url as URL)
theRequest.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
theRequest.addValue((soapMessage), forHTTPHeaderField: "Content-Length")
theRequest.httpMethod = "POST"
theRequest.httpBody = soapMessage.data(using: String.Encoding.utf8, allowLossyConversion: false)
let connection = NSURLConnection(request: theRequest as URLRequest, delegate: self, startImmediately: true)
connection!.start()
}
}
private func connection(connection: NSURLConnection!, didReceiveResponse response: URLResponse!) {
mutableData.length = 0;
}
private func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
mutableData.append(data as Data)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
let xmlParser = XMLParser(data: mutableData as Data)
xmlParser.delegate = self
xmlParser.parse()
xmlParser.shouldResolveExternalEntities = true
}
func parser(_ parser: XMLParser, foundCharacters string: String)
{
if currentElementName == "CelsiusToFahrenheit"
{
txtFahrenheit.text = string
}
}
}