Swift ios with Soap Wcf Web service - ios

Can anybody help on connecting issue swift ios with soap object
var soapMessage = "<?xml version='1.0' encoding='UTF-8'?><soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'><soap:Body> <BindCategory xmlns=‘http://tempuri.org/'></BindCategory></soap:Body></soap:Envelope>"
var urlString = "http://assetwebservice.sudesi.in/service.svc"
var msgLength = String(count(soapMessage))
var url = NSURL(string: urlString)!
var theRequest = NSMutableURLRequest(URL: url)
theRequest.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
theRequest.addValue("http://tempuri.org/IService/BindCategory", forHTTPHeaderField: "Soapaction")
theRequest.addValue(msgLength, forHTTPHeaderField: "Content-Length")
theRequest.HTTPMethod = "POST"
theRequest.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
var connection = NSURLConnection(request: theRequest, delegate: self,startImmediately: true)
connection?.start()
if (connection == true) {
println("Connection success")
var mutableData : Void = NSMutableData.initialize()
}else{
println("Error in connection")
}

Well, the thing that jumps out at me is the following:
if (connection == true) {
println("Connection success")
// What does this line mean? I can't make sense of it.
var mutableData : Void = NSMutableData.initialize()
}
You are comparing an NSURLConnection? to a Bool. This is never going to be true. Besides, this is not the correct way to determine whether a connection is successful. NSURLConnection has an optional initializer so that it can check whether its parameters are valid, not so that the success of a connection can be determined. Success will be determined by the appropriate callbacks to the delegate.
You should look into using NSURLSession instead of NSURLConnection unless you have to support iOS < 7.0, which I doubt. I have a suspicion—perhaps false—that the questioner is a C# programmer doing Swift who is perhaps not familiar with the delegate pattern, which is common in Apple's frameworks but not common at all in Microsoft's. If so, NSURLSession's interface will be much more palatable.

Issue is in soap envevlope mapping , now I have correct that , all things are now perfect.
Thanks

Related

How to stop task or section from NSURLSession

I am Using NSURLSession for call an post API, but when i turn of the wifi and then hit the web service and again turn on the wifi NSURLSession is calling that previously call web service, i want to stop this process. i read on some of documents that NSURLSession store the section of every service call when connection break in any situation , and again hit that service when connection established again. So now i am not getting any solution to stop that service call after connection reconnect to my device.
Any one please help me. Thanks in advance.
Below is my code i used.
let token: NSString!
let urlPath: NSURL!
if provider .isEqualToString("No"){
urlPath = NSURL(string: kAPI_SERVERBASEURL + (url as String))
}
else{
urlPath = NSURL(string: kAPI_SERVERBASEURLSEARCHPROVIDER + (url as String))
}
var postJsonData = NSData()
var jsonString = NSString()
do {
postJsonData = try NSJSONSerialization.dataWithJSONObject(dictRequest, options:[])
jsonString = NSString(data: postJsonData, encoding: NSUTF8StringEncoding)!
NSLog("request - %#", jsonString);
// do other stuff on success
} catch {
print("JSON serialization failed: \(error)")
}
let request = NSMutableURLRequest(URL: urlPath);
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
request.HTTPShouldHandleCookies = false
request.timeoutInterval = 120 ;
request.HTTPMethod = "POST";
if NSUserDefaults.standardUserDefaults().valueForKey(kAccessToken) != nil{
token = NSUserDefaults.standardUserDefaults().valueForKey(kAccessToken) as! NSString
//token = "tk_1vNoEoZRxJwY"
request.setValue("\(token)", forHTTPHeaderField: "access_token")
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPBody = postJsonData
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
`
It may help you.
1.Declare one variable about the NSURLSessionTask like
var task: NSURLSessionTask? = nil
2.When ever you need to call dataTaskWithRequest assign the object to declared object like
task = NSURLSession.sharedSession().dataTaskWithURL(NSURL(fileURLWithPath: ""))
3.when you want to cancel the request just do the below.
if nil != task {
task!.cancel()
task = nil
}
Suppose you want cancel the request before calling another one combine both 2 and 3 steps like
if nil != task {
task!.cancel()
task = nil
}
task = NSURLSession.sharedSession().dataTaskWithURL(NSURL(fileURLWithPath: ""))

I am not able to make a POST request in swift

I am unable to make a successful POST request in swift. It shows an the following
error"kCFStreamErrorCodeKey=-9847,NSErrorFailingURLStringKey=https://192.168.1.167:8100/Attendance/login,".
It worked perfectly with my older version of swift. Now I have updated my Xcode and this issue occurred.
func logSetRequest(){
let urlString = "https://192.168.1.167:8100/Attendance/login"
let url = NSURL(string: urlString)
let theRequest = NSMutableURLRequest(URL: url!)
theRequest.HTTPMethod = "POST"
let parameters = [ "email": usernameTxtField.text!,"password": passwordTxtField.text!] as Dictionary<String, String>
var err: NSError?
do {
theRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: [])
} catch let error as NSError {
err = error
theRequest.HTTPBody = nil
} // pass dictionary to nsdata object and set it as request body
theRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
theRequest.addValue("application/json", forHTTPHeaderField: "Accept")
var connectRequest = NSURLConnection(request: theRequest, delegate: self)
logActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
I have made relevant changes in plist also
From googling it seems that error code -9847 has something to do with SSLHandshake failing.
You said that you've upgraded to a new version of Swift. In iOS 9.0/OS X 10.11 Apple introduced App Transport Security, which requires you to run HTTPS, which you also do. But maybe there is something wrong with the HTTPS setup that worked before, but has stopped working under iOS 9.
You can read more about ATS (and how to temporarily disable it) here:
http://ste.vn/2015/06/10/configuring-app-transport-security-ios-9-osx-10-11/
Hope that helps

NSURLRequest produce different result than HTTP proxy client

I send the same HTTP message from a HTTP proxy client and with NSURLRequest + NSURLConnection, and get back different result. It is an authentication request. From HTTP proxy authentication request is accepted, sending from app not. Why? Accepted means after redirection HTML will contains no Oops substring.
let url = NSURL(string: "http://www.swisshttp.weact.ch/en/user/login")
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let email2 = (viewController!.email.text as NSString).stringByReplacingOccurrencesOfString("#", withString: "%40")
let str = "name=\(email2)&pass=\(viewController!.password.text)&form_id=user_login" as NSString
let d = str.dataUsingEncoding(NSUTF8StringEncoding)
if let d2 = d {
request.HTTPBody = d2
let urlConnection = NSURLConnection(request: request, delegate: self)
}
UPDATE
I have put #teamnorge's code below into playground and into an empty Single View Application project. Returned HTML in project contains the Oops substring, code used in playground not containes it, any idea what is going on, why same request produce different HTML result? I get failed message also from iOS device and from simulator too.
UPDATE
Removed NSURLRequest cache like here recommended, but still not works as expected. And here.
UPDATE
Tried to remove all the credentials like here, but didn't help, no credential was found.
It looks like when you receive HTTP 302 and new Location URL, iOS does automatically fetch the page by this URL, so I guess your response is in fact the HTML content of the redirection page. Please verify.
UPDATE:
import UIKit
import XCPlayground
let url = NSURL(string: "http://www.swisshttp.weact.ch/en/user/login")
let request = NSMutableURLRequest(URL: url!)
let str = "name=kukodajanos%40icloud.com&pass=jelszo&form_id=user_login" as NSString
let d = str.dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = d
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.currentQueue()) { response, maybeData, error in
if let data = maybeData {
let contents = NSString(data:data, encoding:NSUTF8StringEncoding)
println(contents)
if contents!.rangeOfString("Oops").length == 0 {
println("success")
} else {
println("failed")
}
} else {
println(error.localizedDescription)
}
}
XCPSetExecutionShouldContinueIndefinitely()

How to consume WCF .svc service in iOS 8 using swift?

I am beginner in iOS & i want to call WCF .svc service from my application using swift.
My service return soap data in response.
I have consumed asmx service using following code ,can same code be used to call wcf .svc service or i do need to change the code.
var celcius = txtCelsius.text
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/'><Celsius>\(celcius)</Celsius></CelsiusToFahrenheit></soap:Body></soap:Envelope>"
var urlString = "http://www.w3schools.com/webservices/tempconvert.asmx"
var url:NSURL = NSURL(string: urlString)!
var theRequest = NSMutableURLRequest(URL: url)
var msgLength = String(countElements(soapMessage))
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
var connection = NSURLConnection(request: theRequest, delegate: self, startImmediately: true)
connection?.start()
if (connection == true) {
var mutableData : Void = NSMutableData.initialize()
}
Please help me .
var urlString = "http://assetwebservice.sudesi.in/service.svc"
var msgLength = String(count(soapMessage))
var url = NSURL(string: urlString)!
var theRequest = NSMutableURLRequest(URL: url)
theRequest.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
theRequest.addValue("http://tempuri.org/IService/BindCategory", forHTTPHeaderField: "Soapaction")
theRequest.addValue(msgLength, forHTTPHeaderField: "Content-Length")
theRequest.HTTPMethod = "POST"
theRequest.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
var connection = NSURLConnection(request: theRequest, delegate: self,startImmediately: true)
connection?.start()
if (connection == true) {
println("Connection success")
var mutableData : Void = NSMutableData.initialize()
}else{
println("Error in connection")
}
Hi Please check it always be in else condition means Error in connection
Can't get result
Thanks

Error fetching swift post variables

i have created a HTTP POST request in swift ios. when i fetch a post variables in php file, it is showing blank, i am not getting a variable value. below my swift code, look it.
var dataString = "name=john&type=student"
var request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: "http://www.example.com/example.php")
var postString = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPBody = postString
var connection = NSURLConnection(request: request, delegate: self, startImmediately: false)
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
//New request so we need to clear the data object
println(response)
}
Php code:
<?php
echo $_POST['name'];
?>
Anyone can suggest what should i do for getting a variables value. Thanks
You should use a Content-Type of application/x-www-form-urlencoded instead of application/json

Resources