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

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

Related

What's wrong i'm trying to post data using soap api but it's show me http 500 error

I'm trying to post in server but it doesn't connect to server .in this
Status Code: 500, Headers {"Cache-Control" = ( private ); "Content-Length" = ( 236
I've never used SOAP API. Can anyone help me? If you have any better solution then provide me.
import UIKit
class ViewController: UIViewController {
var is_SoapMessage = String(format: "<?xml version='1.0'
encoding='utf-8'?>\n" +
"<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/'>\n" +
"<soap:Body>\n"
+ "<QR_GetDeviceCtration
xmlns='http://www.bdmitech.com/m2b'>\n"
+ "<TerminalName>%#</TerminalName>\n"
+ "<TerminalSerial>%#</TerminalSerial>\n"
+ "<ChannelType>%#</ChannelType>\n"
+ "<SecurityKey>%#</SecurityKey>\n"
+ "</QR_GetDeviceCheckAndRegistration>\n"
+ "</soap:Body></soap:Envelope>\n"
,"wegg","gewg","gerg","gerw","khds")
override func viewDidLoad() {
super.viewDidLoad()
self.soapcall()
}
func soapcall(){
let is_URL: String = "http://27.147.34.sdfre/eckAndRegistration"
let lobj_Request = NSMutableURLRequest(url: NSURL(string: is_URL)! as URL)
//let session = URLSession.shared
//let err: NSError?
let msgLength = String(describing: is_SoapMessage.characters.count)
lobj_Request.httpMethod = "POST"
// lobj_Request.httpBody = is_SoapMessage.data(using: String.Encoding.utf8)
lobj_Request.addValue("27.43.3553.32", forHTTPHeaderField: "Host")
lobj_Request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
lobj_Request.addValue(msgLength, forHTTPHeaderField: "Content-Length")
lobj_Request.httpBody = is_SoapMessage.data(using: String.Encoding.utf8)
lobj_Request.addValue("http://27.32423.23423.245:98/dRegistration", forHTTPHeaderField: "SOAPAction")
let session = URLSession(configuration: URLSessionConfiguration.default)
let task: URLSessionDataTask = session.dataTask(with: lobj_Request as URLRequest ) { (data, response, error) in
print(response)
}
task.resume()
}
}

Unable to POST a request in swift

let urlString = "https://192.168.1.167:8090/Attendance/register"
let url = NSURL(string: urlString)
let theRequest = NSMutableURLRequest(URL: url!)
theRequest.HTTPMethod = "POST"
let parameters = ["firsrtName": regFirstNameTxtField.text!, "lastName": regLastNameTxtField.text!,"email": regEmailTxtField.text!,"password": regPassWordTxtField.text!,"phone": regPhoneNoTxtField.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)
I am unable to post a request in swift. It worked perfectly with my older version of xcode. But now when I run it shows the following error message : UserInfo={NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made.,
SErrorFailingURLKey=https://192.168.1.167:8090/Attendance/register}

Get error status code webview swift 2

I want to get error status code when my WebView is loaded.
When I open the connexion I use this code :
let simpler = "http://www.example.com"
let url = NSURL(string: simpler)
let request = NSURLRequest(URL: url!)
webview.loadRequest(request)
I have found this code but I obtain errors so it's not working :
Check URL of Loaded WebView
I want to get the errors in the ViewDidLoad
Try this one :-
var url:NSURL = NSURL(string: "http://www.example.com")!
var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
var postLength:NSString = String( postData.length )
var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
//request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("*/*", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
let res = response as! NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);

getting 403 forbidden when access sharepoint web service from ios in swift

I am new to ios development and i am trying to access sharepoint web service from ios but i getting 403 forbidden in response
I have also refer to this link for authentication but it doesn't work
Then I try to authenticate using didReceiveAuthenticationChallenge method which i refer from this link
As per the developer.apple.com documentation this method is deprecated and i use willSendRequestForAuthenticationChallenge method
Following is Code
var message:String = "<?xml version='1.0' encoding='utf-8'?><soap12:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap12='http://www.w3.org/2003/05/soap-envelope'><soap12:Body><GetList xmlns='http://schemas.microsoft.com/sharepoint/soap/'><listName>ThemeGallery</listName></GetList></soap12:Body></soap12:Envelope>"
var urlString = "https://domainname/_vti_bin/Lists.asmx"
var url = NSURL(string: urlString)
var req = NSMutableURLRequest(URL: url!)
var msglength = String(countElements(message))
req.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
req.addValue(msglength, forHTTPHeaderField: "Content-Length")
req.addValue("http://schemas.microsoft.com/sharepoint/soap/GetList", forHTTPHeaderField: "SOAPAction")
req.HTTPMethod = "POST"
req.HTTPBody = message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
var connection = NSURLConnection(request: req, delegate: self, startImmediately: true)
connection?.start()
Connection Methods
func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge) {
if challenge.previousFailureCount == 0
{
var newCredential = NSURLCredential(user: self.username, password: self.password, persistence: NSURLCredentialPersistence.ForSession)
challenge.sender.useCredential(newCredential, forAuthenticationChallenge: challenge)
}
else
{
challenge.sender.cancelAuthenticationChallenge(challenge)
}
}
Parsing Methods
func connectionDidFinishLoading(connection: NSURLConnection!) {
var xmlParser = NSXMLParser(data: self.mutableData)
xmlParser.delegate = self
xmlParser.parse()
xmlParser.shouldResolveExternalEntities = true
}
I have got solution for authentication to share point web service
I have use FedAuth Cookie and rtFa Cookie to pass credential
Fisrt I have load the sharepoint login page in UIWebView
When user successfully log in. We have to get those Cookies by Below method
func verifyCookies()
{
var rtFa:NSHTTPCookie?
var fedAuth:NSHTTPCookie?
let storage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
let cookieArray = storage.cookies!
for tempCookie in cookieArray
{
if tempCookie.name == "rtFa"
{
rtFa = tempCookie as? NSHTTPCookie
continue
}
else if tempCookie.name == "FedAuth"
{
fedAuth = tempCookie as? NSHTTPCookie
continue
}
}
if rtFa != nil && fedAuth != nil
{
self.webView.hidden = true
self.cookieFound(rtFa!,fedAuthCookie: fedAuth!) // method mention below.
}
}
And after that I have use those cookie to pass credential to my request.
Below is my request code
func cookieFound(rtFaCookie:NSHTTPCookie,fedAuthCookie:NSHTTPCookie)
{
var message:String = "<?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><GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'><listName>demo</listName><viewName></viewName><query></query><viewFields></viewFields><rowLimit></rowLimit><QueryOptions></QueryOptions><webID></webID></GetListItems></soap:Body></soap:Envelope>"
var messageLength = String(countElements(message))
var url = NSURL(string: "https://domain/_vti_bin/Lists.asmx")
var therequest = NSMutableURLRequest(URL: url!)
therequest.addValue(messageLength, forHTTPHeaderField: "Content-Length")
therequest.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
therequest.addValue("http://schemas.microsoft.com/sharepoint/soap/GetListItems", forHTTPHeaderField: "SOAPAction")
// Authentication is passed in request header
var cookieArray = NSArray(objects: rtFaCookie,fedAuthCookie)
var cookieHeaders = NSHTTPCookie.requestHeaderFieldsWithCookies(cookieArray)
var requestHeaders = NSDictionary(dictionary: cookieHeaders)
therequest.allHTTPHeaderFields = requestHeaders
therequest.HTTPMethod = "POST"
therequest.HTTPBody = message.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
var connection = NSURLConnection(request: therequest, delegate: self, startImmediately: true)
connection?.start()
}
I have called verifyCookies() method from below 'UIWebView delegate' methods
func webViewDidStartLoad(webView: UIWebView) {
self.verifyCookies()
}
func webViewDidFinishLoad(webView: UIWebView) {
self.verifyCookies()
}
Hope it will help someone
Check to see if it works from a command line invocation of a utility like curl i.e. something like
curl -D- -u user:password http://....
If you see a 403 there, it's likely that Sharepoint doesn't accept HTTP basic authentication, and your code won't work.

How to post a JSON with new Apple Swift Language

I'm (trying to) learn the Swift's Apple language. I'm at Playground and using Xcode 6 Beta. I'm trying to do a simple JSON Post to a local NodeJS server. I already had googled about it and the major tutorials explain how to do it in a project, not at PLAYGROUND, than don't write stupid thinks like: "google it" or "it's obvious" or "look this link" or never-tested-and-not-functional-code
This is what i'm trying:
var request = NSURLRequest(URL: NSURL(string: "http://localhost:3000"), cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
var response : NSURLResponse?
var error : NSError?
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
I had tried:
var dataString = "some data"
var request = NSMutableURLRequest(URL: NSURL(string: "http://posttestserver.com/post.php"))
request.HTTPMethod = "POST"
let data = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
var requestBodyData: NSData = data
request.HTTPBody = requestBodyData
var connection = NSURLConnection(request: request, delegate: nil, startImmediately: false)
println("sending request...")
connection.start()
Thank you! :)
Nate's answer was great but I had to change the request.setvalue for it to work on my server
// create the request & response
var request = NSMutableURLRequest(URL: NSURL(string: "http://requestb.in/1ema2pl1"), cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
var response: NSURLResponse?
var error: NSError?
// create some JSON data and configure the request
let jsonString = "json=[{\"str\":\"Hello\",\"num\":1},{\"str\":\"Goodbye\",\"num\":99}]"
request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
// send the request
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
// look at the response
if let httpResponse = response as? NSHTTPURLResponse {
println("HTTP response: \(httpResponse.statusCode)")
} else {
println("No HTTP response")
}
It looks like you have all the right pieces, just not in quite the right order:
// create the request & response
var request = NSMutableURLRequest(URL: NSURL(string: "http://requestb.in/1ema2pl1"), cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
var response: NSURLResponse?
var error: NSError?
// create some JSON data and configure the request
let jsonString = "json=[{\"str\":\"Hello\",\"num\":1},{\"str\":\"Goodbye\",\"num\":99}]"
request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
// send the request
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
// look at the response
if let httpResponse = response as? NSHTTPURLResponse {
println("HTTP response: \(httpResponse.statusCode)")
} else {
println("No HTTP response")
}
Here is a little different approach using asynchronous request. You can use synchronous approach this way too but since everyone above used synchronous request, I thought show asynchronous request instead. Another thing is it seems cleaner and easier this way.
let JSONObject: [String : AnyObject] = [
"name" : name,
"address" : address,
"phone": phoneNumber
]
if NSJSONSerialization.isValidJSONObject(JSONObject) {
var request: NSMutableURLRequest = NSMutableURLRequest()
let url = "http://tendinsights.com/user"
var err: NSError?
request.URL = NSURL(string: url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(JSONObject, options: NSJSONWritingOptions(rawValue:0), error: &err)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) {(response, data, error) -> Void in
if error != nil {
println("error")
} else {
println(response)
}
}
}

Resources