2017-05-08 81 views
0

我想使用下面的代碼在iOS中快速調用.net framework asmx web服務(soap)。在swift 3和xcode 8+中調用.NET asmx

@IBAction func buttonTest(_ sender: Any) { 

    var soapMessage = "<?xml version='1.0' encoding='utf-8'?>"; 
    soapMessage = soapMessage + "<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/'>"; 
    soapMessage = soapMessage + "<soap:Body>"; 
    soapMessage = soapMessage + "<LogginCustomerClub xmlns='http://tempuri.org/'>"; 
    soapMessage = soapMessage + "<userName>username</userName>"; 
    soapMessage = soapMessage + "<password>pass</password>"; 
    soapMessage = soapMessage + "<message>message</message>"; 
    soapMessage = soapMessage + "</LogginCustomerClub>"; 
    soapMessage = soapMessage + "</soap:Body>"; 
    soapMessage = soapMessage + "</soap:Envelope>"; 

    let urlString = "http://example.com/users.asmx" 
    let url = NSURL(string: urlString) 
    let theRequest = NSMutableURLRequest(url: url! as URL) 

    let msgLength = String(soapMessage.characters.count) 

    theRequest.addValue("text/xml; charset=utf-B", forHTTPHeaderField: "Content-Type") 

    theRequest.addValue(String(msgLength), forHTTPHeaderField: "Content-Length") 

    theRequest.httpMethod = "POST" 

    theRequest.httpBody = soapMessage.data(using: .utf8) 

    //theRequest.httpBody = soapMessage.dataUsIngEncoding (NSUTF8StringEncoding, allowLossyConversion: false) // or false 

    let connection = NSURLConnection(request: theRequest as URLRequest, delegate: self, startImmediately: true) 

    connection!.start() 

    if (connection != nil) 
    { 
     var mutableData = NSMutableData.initialize() 
    } 
} 
func connection(connection: NSURLConnection, didReceiveResponse response: URLResponse!) 

{ 
    mutableData.length = 0; 
} 

func connection(connection: NSURLConnection, didReceiveData data: NSData!) 
{ 
    mutableData.append(data as Data) 
} 
func connectionDidFinishLoading(connection: NSURLConnection!) 
{ 
    let response = NSString(data: mutableData as Data, encoding: String.Encoding.utf8.rawValue) 

    let xmlParser = XMLParser(data: mutableData as Data) 
    xmlParser.delegate = self 
    xmlParser.parse() 
    xmlParser.shouldResolveExternalEntities = true 
} 
    // NSXMLParserDelegate 

func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { 

    currentElementName = elementName as NSString 
} 
func parser(parser: XMLParser,foundCharacters string: String?) 
{ 
    if currentElementName == "LoginResult"{ 
     print(string) 
    } 
} 

項目建立成功,但我無法得到響應。 我不知道我在做什麼錯。

任何幫助,將不勝感激

回答

相關問題