공개적으로 사용 가능한 웹 서비스에 SOAP 메시지를 신속하게 전달하고 있습니다. SOAP 응답을 받고 있으며 NSXMLParser를 사용하여 이것을 구문 분석하려고 시도하고 있음을 알 수 있습니다.
foundCharacters 매개 변수 가있는 파서 메서드를 사용 하려고 했지만 한 번만 호출되고 "Error"문자열 만 포함됩니다.
CelsiusToFahrenheitResult 태그에 포함되어야한다고 생각하는 결과에 액세스하고 싶습니다.
내가 호출하는 웹 서비스와 SOAP 메시지는 여기 에서 찾을 수 있습니다.
응답에 다음 요소가 포함되어 있음을 알 수 있습니다.
그런데 왜 여기에있는 값이 인쇄되지 않습니까?
비슷한 질문은 여기에서 찾을 수 있습니다 : Swift와 함께 NSXMLParser를 사용하여 SOAP 응답을 구문 분석 하지만 완전한 대답이 없습니다.
버튼을 누를 때 웹 서비스를 호출하는 내 뷰 컨트롤러의 전체 코드 :
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, NSURLConnectionDelegate, NSXMLParserDelegate {
var mutableData:NSMutableData = NSMutableData.alloc()
@IBOutlet weak var button: UIButton!
@IBOutlet weak var textfield: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
// These counts are just for my own reference - checking these later.
var didStartElement = 0
var didEndElement = 0
var foundCharacters = 0
func callWebService(){
// This would likely be taken from an input.
var celcius = "10";
var 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/tempconvert.asmx'><Celsius>\(celcius)</Celsius></CelsiusToFahrenheit></soap:Body></soap:Envelope>"
println(soapMessage);
var urlString = "http://www.w3schools.com/webservices/tempconvert.asmx?op=CelsiusToFahrenheit"
var url = NSURL(string: urlString)
var theRequest = NSMutableURLRequest(URL: url!)
var msgLength = String(count(soapMessage))
theRequest.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
theRequest.addValue(msgLength, forHTTPHeaderField: "Content-Length")
theRequest.addValue("http://www.w3schools.com/webservices/CelsiusToFahrenheit", forHTTPHeaderField: "SOAPAction")
theRequest.HTTPMethod = "POST"
theRequest.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
var connection = NSURLConnection(request: theRequest, delegate: self, startImmediately: true)
// Do NOT call start since the above call will start the connection
}
@IBAction func convertButtonClicked(sender: AnyObject) {
callWebService();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
println(response);
if let httpResponse = response as? NSHTTPURLResponse {
// Just printing the status code here.
println("error \(httpResponse.statusCode)")
}
// We got a response to set the length of the data to zero since we will be adding to this
// if we actually got any data back.
mutableData.length = 0;
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
mutableData.appendData(data)
}
// Parse the result right after loading
func connectionDidFinishLoading(connection: NSURLConnection!) {
println(mutableData)
var xmlParser = NSXMLParser(data: mutableData)
xmlParser.delegate = self
xmlParser.shouldProcessNamespaces = false
xmlParser.shouldReportNamespacePrefixes = false
xmlParser.shouldResolveExternalEntities = false
xmlParser.parse()
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject]) {
didStartElement += 1
// Can see elements in the soap response being printed.
println(elementName);
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
didEndElement += 1
}
func parser(parser: NSXMLParser, foundCharacters string: String?) {
foundCharacters += 1
// This prints "Error"
println("found chars: \(string!)");
}
}
문제는 NSXMLParser
. 요청 SOAP 메시지에 문제가 있습니다. 올바른 네임 스페이스를 사용하는지 확인하십시오.
였다:
<CelsiusToFahrenheit xmlns='http://www.w3schools.com/webservices/tempconvert.asmx'>
결정된:
<CelsiusToFahrenheit xmlns="http://www.w3schools.com/webservices/">
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다