0

I was starting to migrate my old objective-c SOAP Web Service code to Swift 2. But I failed as I never got a response using Swift 2 which drove me nuts at the end.

I started isolating things and following this Soap temperature converter tutorial (http://webindream.com/soap-with-swift/) which is Swift 1.2 based.

This is my Swift 2 converted ViewController but connection never got true (connection == truenever occurred).

//
//  ViewController.swift
//  Temperature Converter
//
//  Created by Farhad on 10/24/14.
//  Copyright (c) 2014 Web In Dream. All rights reserved.
//

import UIKit

//Step 1: Add protocol names that we will be delegating.

class ViewController: UIViewController, UITextFieldDelegate, NSURLConnectionDelegate, NSXMLParserDelegate {

    var mutableData:NSMutableData  = NSMutableData()
    var currentElementName:NSString = ""



    @IBOutlet var txtCelsius : UITextField!
    @IBOutlet var txtFahrenheit : UITextField!


    @IBAction func actionConvert(sender : AnyObject) {
        let celcius = txtCelsius.text

        let 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>\(celcius)</Celsius></CelsiusToFahrenheit></soap:Body></soap:Envelope>"


        let urlString = "http://www.w3schools.com/webservices/tempconvert.asmx"

        let url = NSURL(string: urlString)

        let theRequest = NSMutableURLRequest(URL: url!)

        let msgLength = String(soapMessage.characters.count)

        theRequest.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
        theRequest.addValue(msgLength, forHTTPHeaderField: "Content-Length")
        theRequest.HTTPMethod = "POST"
        theRequest.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) // or false

        let connection = NSURLConnection(request: theRequest, delegate: self, startImmediately: true)
        connection!.start()

        if (connection == true) {
            var mutableData : NSMutableData = NSMutableData()
        }


    }




    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    // NSURLConnectionDelegate

    // NSURL



    func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
        mutableData.length = 0;
    }

    func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
        mutableData.appendData(data)
    }


    func connectionDidFinishLoading(connection: NSURLConnection!) {
        let xmlParser = NSXMLParser(data: mutableData)
        xmlParser.delegate = self
        xmlParser.parse()
        xmlParser.shouldResolveExternalEntities = true

    }


    // NSXMLParserDelegate

    func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
        currentElementName = elementName

    }



    func parser(parser: NSXMLParser!, foundCharacters string: String!) {
        if currentElementName == "CelsiusToFahrenheitResult" {
            txtFahrenheit.text = string
        }
    }



}

There have been a lot of coments around in the internet but no real answer why connection never gets true with Swift 2. At least no one solved my problem finally ;-(

That's the reason I raise this question again with hope getting a working version for the community. Is there anybody out there made a successful Swift 2.1 SOAP Web Service Call and could share the solution?

Many thanks in advance John

John B.
  • 682
  • 1
  • 11
  • 22
  • Hi, I'm working on soap to, and I had to update too, have you found a solution ? – B.Benj Dec 23 '15 at 14:50
  • Hi @B.Benj, the solution posted worked as soon as I fixed what @HoaParis mentioned, that `NSUrlConnection` is not a boolean, so I changed it to `if(connection != nil) ...`. So hope this helps you too. Cheers, John – John B. Dec 24 '15 at 09:40
  • Sure thanks, but now I get an another problem by passing on Swift2 it doesn't accept IP :( Thanks – B.Benj Jan 07 '16 at 08:47
  • Hi @B.Benj, good to hear you are making progress. I do not completely understand what error you are getting if you are saying "it doesn't accept IP". Could you give me some more information. – John B. Jan 07 '16 at 12:50
  • Here the subject: http://stackoverflow.com/questions/34654745/soap-in-swift-2-kcfstreamerrordomainssl?s=2|0.0000 – B.Benj Jan 07 '16 at 12:55
  • @JohnB. Have you finished this tutorial? I will be really grateful if you post working code here. – wm.p1us Jan 26 '16 at 03:49
  • @JohnB. hi john, I have the same problem with swift2.1 have you fixed your code problem ? is it working ! if yes can you put a tutorial so others like me be able to use it. – anonymox Feb 07 '16 at 10:33

1 Answers1

1

First of all, you should use NSUrlSession instead of NSUrlConnection cause this class is obsoleted in iOS9.

Second, your connection is a NSURLConnection?, you have to compare it with 'nil' instead of 'true'. It's not a boolean. So the code var mutableData : NSMutableData = NSMutableData() will never get called.

If you test in iOS9, you have to add some setting to your application. Otherwise, you will get error during connection process. Take a look at this topic: How do I load an HTTP URL with App Transport Security enabled in iOS 9?

Community
  • 1
  • 1
Duyen-Hoa
  • 15,384
  • 5
  • 35
  • 44
  • Hi HoaParis, thanks for the reply. The line _italic_NSURLConnection is not a boolean_italic_ at the end was the hint. After correcting this it worked. I had already adapted the `info.plist` file to not run in the "insecure connection" thing. So after having the first bit working I will try to use now `NSUrlSession`instead. Cheers John – John B. Dec 02 '15 at 08:16