I am trying to implement HTTP requests.
Here is the objective C implementation
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
I started by writing:
let request = NSMutableURLRequest()
request .setValue(postLength, forHTTPHeaderField: "Content-Lenght")
request .setValue(application/json, forHTTPHeaderField: Accept)
1.The json request is giving me an error.
2.I cannot convert the setURL and SetHTTPBody from objective C to swift. I could not find
the option for these.
Any help would be appreciated.
Thank you.
They have become properties. Most setter methods with a single argument have become properties.
The problem with your json line is you did not have quotes around "Accept."
let request = NSMutableURLRequest()
request.url = url
request.HTTPMethod = "POST"
request.setValue(postLength, forHTTPHeaderField:"Content-Length")
request.setValue("application/json", forHTTPHeaderField:"Accept")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type")
request.postBody = postData
Here is how i do it in swift :
var request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "POST"
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPBody = jsonData
var request: NSMutableURLRequest?
let HTTPMethod: String = "POST"
var timeoutInterval: NSTimeInterval = 60
var HTTPShouldHandleCookies: Bool = false
request = NSMutableURLRequest(URL: url)
request!.HTTPMethod = HTTPMethod
request!.timeoutInterval = timeoutInterval
request!.HTTPShouldHandleCookies = HTTPShouldHandleCookies
let boundary = "----------SwIfTeRhTtPrEqUeStBoUnDaRy"
let contentType = "multipart/form-data; boundary=\(boundary)"
request!.setValue(contentType, forHTTPHeaderField:"Content-Type")
var body = NSMutableData();
let tempData = NSMutableData()
let fileName = filenames + ".jpg" //"prueba.jpg"
let parameterName = "userfile"
let mimeType = "application/octet-stream"
tempData.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
let fileNameContentDisposition = fileName != nil ? "filename=\"\(fileName)\"" : ""
let contentDisposition = "Content-Disposition: form-data; name=\"\(parameterName)\"; \(fileNameContentDisposition)\r\n"
tempData.appendData(contentDisposition.dataUsingEncoding(NSUTF8StringEncoding)!)
tempData.appendData("Content-Type: \(mimeType)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
tempData.appendData(imageData)
tempData.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(tempData)
body.appendData("\r\n--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
request!.setValue("\(body.length)", forHTTPHeaderField: "Content-Length")
request!.HTTPBody = body
var vl_error :NSErrorPointer = nil
var responseData = NSURLConnection.sendSynchronousRequest(request,returningResponse: nil, error:vl_error)
var results = NSString(data:responseData, encoding:NSUTF8StringEncoding)
println("finish \(results)")
I am calling the json on login button click
#IBAction func loginClicked(sender : AnyObject){
var request = NSMutableURLRequest(URL: NSURL(string: kLoginURL)) // Here, kLogin contains the Login API.
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(self.criteriaDic(), options: nil, error: &err) // This Line fills the web service with required parameters.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err1: NSError?
var json2 = NSJSONSerialization.JSONObjectWithData(strData.dataUsingEncoding(NSUTF8StringEncoding), options: .MutableLeaves, error:&err1 ) as NSDictionary
if(err) {
println(err!.localizedDescription)
}
else {
var success = json2["success"] as? Int
println("Succes: \(success)")
}
})
task.resume()
}
Here, I have made a seperate dictionary for the parameters.
var params = ["format":"json", "MobileType":"IOS","MIN":"f8d16d98ad12acdbbe1de647414495ec","UserName":emailTxtField.text,"PWD":passwordTxtField.text,"SigninVia":"SH"] as NSDictionary
return params
}
Related
If I post raw data using Postman, response is coming. I am using this code
var dict = Dictionary<String, Any>()
dict = ["user_id" :userid as AnyObject, "type" :type as AnyObject, "complaint_id" :complaintId as AnyObject, "auth_code" : authCode as AnyObject, "isSkip" :isSkip as AnyObject]
let url:URL = URL(string: "http://development.easystartup.org/prigovo/Backend/detailed_complaint/index.php")!
let session = URLSession.shared
var postData = NSData()
do{
postData = try JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions.prettyPrinted) as NSData!
}catch {
print("error")
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
// request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
request.setValue("\(postData.length)", forHTTPHeaderField: "Content-Length")
request.setValue("text/html", forHTTPHeaderField: "Content-Type")
request.setValue("json/application", forHTTPHeaderField: "Accept")
request.httpBody = postData as Data
let task = session.dataTask(with: request as URLRequest) {
(
data, response, error) in
guard let data = data, let _:URLResponse = response, error == nil else {
print("error")
return
}
let dataString = String(data: data, encoding: String.Encoding.utf8)
print(dataString ?? "no data")
}
task.resume()
Getting data of 0 bytes everyTime. Already tried with Alamofire but no response.
Also I tried in Objective C where I am getting response, code is :
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)postData.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"text/html" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = nil;
NSHTTPURLResponse *response = nil;
[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSData *retData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error)
{
//error
NSLog(#"error");
return #"";
}
else
{
NSLog(#"No error");
NSString *charlieSendString = [[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding];
NSLog(#"data come : %#",charlieSendString);
return charlieSendString;
}
Posted "dict" in Log :
["complaint_id": COMBRD1, "user_id": USR9, "type": complaint_brand, "auth_code": KL1hwYrAhNVnSgT, "is_skip": 2]
var dict = Dictionary<String, Any>()
dict = ["user_id" :userid, "type" :type, "complaint_id" :complaintId,"auth_code" : authCode, "is_skip" :isSkip]
var jsonData = NSData()
// var dataString2 :String = ""
do {
jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) as NSData
// you can now cast it with the right type
} catch {
print(error.localizedDescription)
}
let url:URL = URL(string: "http://Backend/detailed_complaint/index.php")!
let session = URLSession.shared
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("\(jsonData.length)", forHTTPHeaderField: "Content-Length")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData as Data
let task = session.dataTask(with: request as URLRequest) {
(
data, response, error) in
guard let data = data, let _:URLResponse = response, error == nil else {
print("error")
return
}
let dataString = String(data: data, encoding: String.Encoding.utf8)
print("no data",dataString ?? "no data")
}
task.resume()
My response data isn't to come with parameters.
I used to do it this way which worked:
let str = "https://itunes.apple.com/in/rss/topfreeapplications/limit=2/json"
let dict = ["user":"admin"]
let request = NSMutableURLRequest(url: URL(string: str)!)
request.httpMethod = "POST"
let afManager = AFHTTPSessionManager()
afManager.responseSerializer = AFJSONResponseSerializer()
afManager.requestSerializer = AFJSONRequestSerializer()
afManager.requestSerializer.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
afManager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Accept")
afManager.post(str, parameters: dict, progress: nil, success: { (dataTask, responsedata) in
print(responsedata)
}) { (dataTask, err) in
print(error)
}
I have looked through the answers to how to call a web service via SOAP form swift on the internet and found some answers. I have tried to implement the code I have found in those answers but continually get a http 400 status code. I am trying to figure our what I am doing wrong.
I have distilled the problem down to a few lines of code in a view controller as seen below an the code is called when a button on the UI is pressed. The web service I am trying to call can be found at http://www.cgsapi.com/CGSWebService.asmx.
(To view the WSDL file append ?wsdl to the end of the URL.)
import UIKit
class ViewController: UIViewController {
var is_SoapMessage: String = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:cgs=\"http://www.cgsapi.com/\"><soapenv:Header/><soapenv:Body><cgs:GetSystemStatus/></soapenv:Body></soapenv:Envelope>"
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.
}
#IBAction func btnClicked(sender: AnyObject)
{
var is_URL: String = "http://www.cgsapi.com/CGSWebService.asmx"
var lobj_Request = NSMutableURLRequest(URL: NSURL(string: is_URL)!)
var session = NSURLSession.sharedSession()
var err: NSError?
lobj_Request.HTTPMethod = "POST"
lobj_Request.addValue("www.cgsapi.com", forHTTPHeaderField: "Host")
lobj_Request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
//lobj_Request.addValue(String(count(is_SoapMessage)), forHTTPHeaderField: "Content-Length")
lobj_Request.addValue("223", forHTTPHeaderField: "Content-Length")
lobj_Request.addValue("http://www.cgsapi.com/GetSystemStatus", forHTTPHeaderField: "SOAPAction")
var task = session.dataTaskWithRequest(lobj_Request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
if error != nil
{
println("Error: " + error.description)
}
})
task.resume()
}
}
Any idea why I am getting http 400 status when I call this?
So i was being silly. The main thing was that I missed setting the body of the message to the SOAP request. My updated corrected code is below:
//
// ViewController.swift
// TestWebServiceSoap
//
// Created by George M. Ceaser Jr on 6/2/15.
// Copyright (c) 2015 George M. Ceaser Jr. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var is_SoapMessage: String = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:cgs=\"http://www.cgsapi.com/\"><soapenv:Header/><soapenv:Body><cgs:GetSystemStatus/></soapenv:Body></soapenv:Envelope>"
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.
}
#IBAction func btnClicked(sender: AnyObject)
{
var is_URL: String = "http://www.cgsapi.com/CGSWebService.asmx"
var lobj_Request = NSMutableURLRequest(URL: NSURL(string: is_URL)!)
var session = NSURLSession.sharedSession()
var err: NSError?
lobj_Request.HTTPMethod = "POST"
lobj_Request.HTTPBody = is_SoapMessage.dataUsingEncoding(NSUTF8StringEncoding)
lobj_Request.addValue("www.cgsapi.com", forHTTPHeaderField: "Host")
lobj_Request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
lobj_Request.addValue(String(count(is_SoapMessage)), forHTTPHeaderField: "Content-Length")
//lobj_Request.addValue("223", forHTTPHeaderField: "Content-Length")
lobj_Request.addValue("http://www.cgsapi.com/GetSystemStatus", forHTTPHeaderField: "SOAPAction")
var task = session.dataTaskWithRequest(lobj_Request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
if error != nil
{
println("Error: " + error.description)
}
})
task.resume()
}
}
Swift 5.2, XCode 12
I followed more or less the approach that George did on his self response.
I think that leaving a sample of code with the latest swift and Xcode may be helpful for some:
private func exampleSoapRequest() {
let url = URL(string: ProvidedData.urlString)!
let request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = ProvidedData.envelope.data(using: .utf8)
request.addValue(String(ProvidedData.envelope.count), forHTTPHeaderField: "Content-Length")
request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue("<PUT HERE YOUR SOAP ACTION IF NEEDED>", forHTTPHeaderField: "SOAPAction")
let task = URLSession.shared
.dataTask(with: request as URLRequest,
completionHandler: { data, response, error in
guard error == nil else {
// Handle the error
print(error)
}
guard let data = data else {
return
}
// Continue checking response or data...
})
task.resume()
}
In the ProvidedData, I just assumed you're gonna pass somehow your url and envelope.
In addition to that, if you want to have a more structured and "parameter based" envelope and you don't mind using external libraries, the solution with AEXML proposed by #Pulkit Kumar Singh is also quite interesting.
Refer to this link https://github.com/blastar/Swift-SOAP-with-Alamofire . It gives you a more structured way to deal with Soap with Almofire.
1.Using cocoa pods you can import the following pods
https://cocoapods.org/ to know how to setup cocoa pods
use_frameworks!
target 'Swift-SOAP-with-Alamofire' do
pod 'Alamofire'
pod 'SWXMLHash'
pod 'AEXML'
pod 'StringExtensionHTML'
end
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['CONFIGURATION_BUILD_DIR'] = '$PODS_CONFIGURATION_BUILD_DIR'
end
end
end
2.
This is just a way to implement soap through almofire which is more structured . You have to do a little task to customise according to your implementation
func getCountries(completion: (result: [Country]) -> Void) -> Void {
var result = [Country]()
let soapRequest = AEXMLDocument()
let envelopeAttributes = ["xmlns:SOAP-ENV" : "http://schemas.xmlsoap.org/soap/envelope/", "xmlns:ns1" : "http://www.webserviceX.NET"]
let envelope = soapRequest.addChild(name: "SOAP-ENV:Envelope", attributes: envelopeAttributes)
let body = envelope.addChild(name: "SOAP-ENV:Body")
body.addChild(name: "ns1:GetCountries")
let soapLenth = String(soapRequest.xmlString.characters.count)
let theURL = NSURL(string: "http://www.webservicex.net/country.asmx")
let mutableR = NSMutableURLRequest(URL: theURL!)
mutableR.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
mutableR.addValue("text/html; charset=utf-8", forHTTPHeaderField: "Content-Type")
mutableR.addValue(soapLenth, forHTTPHeaderField: "Content-Length")
mutableR.HTTPMethod = "POST"
mutableR.HTTPBody = soapRequest.xmlString.dataUsingEncoding(NSUTF8StringEncoding)
Alamofire.request(mutableR)
.responseString { response in
if let xmlString = response.result.value {
let xml = SWXMLHash.parse(xmlString)
let body = xml["soap:Envelope"]["soap:Body"]
if let countriesElement = body["GetCountriesResponse"]["GetCountriesResult"].element {
let getCountriesResult = countriesElement.text!
let xmlInner = SWXMLHash.parse(getCountriesResult.stringByDecodingHTMLEntities)
for element in xmlInner["NewDataSet"]["Table"].all {
if let nameElement = element["Name"].element {
var countryStruct = Country()
countryStruct.name = nameElement.text!
result.append(countryStruct)
}
}
}
completion(result: result)
}else{
print("error fetching XML")
}
}
}
Hope it Helps.
You can use below code to make web service call.
let url = NSURL(string: "https://www.google.com/")
var request:NSMutableURLRequest = NSMutableURLRequest(URL:url!)
var bodyData = "data=something"
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
print(response)
if let HTTPResponse = response as? NSHTTPURLResponse {
let statusCode = HTTPResponse.statusCode
if statusCode == 200 {
// Yes, Do something.
}else{
print("Error")
}
}
}
*api calling for returning data type soap
swift 2.2. and above*
let urlForService = NSURL.init(string: "enter your url string")
let postString = String(format: "TokenId=%#&LoggedUserId=%#&UserDeviceId=%#", arguments: ["parameter value","parameter value","parameter value"])
do
{
let urlSession:NSURLSession = NSURLSession.sharedSession()
let urlRequest:NSMutableURLRequest = NSMutableURLRequest(URL: urlForService!)
urlRequest.HTTPShouldHandleCookies = false
urlRequest.timeoutInterval = 120 ;
urlRequest.HTTPMethod = "POST";
urlRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("\(postString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)?.length)", forHTTPHeaderField: "Content-Length")
urlRequest.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
let session = urlSession.dataTaskWithRequest(urlRequest, completionHandler: { (data, response, errorResponse) in
if errorResponse != nil {
print(errorResponse!.localizedDescription)
}
else
{
if data != nil
{
do {
if let dictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary {
let dateformaterweb = NSDateFormatter()
dateformaterweb.dateFormat = "DD/MM/YYYY"
let tempwitnohdate = dictionary.valueForKey("AllContact") as! NSArray
for i in tempwitnohdate{
if String(i.valueForKey("Birthdate")!) != ""{
let name = String(i.valueForKey("ContactName")!)
let number = String(i.valueForKey("ContactNo")!)
let temparray = String(i.valueForKey("Birthdate")!).componentsSeparatedByString("/")
let month = temparray[1]
let day = temparray[0]
let dateweb = ([temparray[0]] + [temparray[1]]).joinWithSeparator(",")
self.usercontact.append(Utility(name: name, number: number, date: dateweb, month:Int(month)!, day:Int(day)!))
}
else{
let name = String(i.valueForKey("ContactName")!)
let number = String(i.valueForKey("ContactNo")!)
let dateweb = self.formater.stringFromDate(self.date)
self.usercontactsort.append(Utility(name: name, number: number, date: dateweb, month:13, day:32))
}
}
self.usercontactsort = self.usercontactsort.sort { $0.strName.localizedStandardCompare($1.strName) == NSComparisonResult.OrderedAscending }
self.usercontact.sortInPlace{$0.monthorder < $1.monthorder}
for i in 0...self.usercontact.count - 1{
for j in i...self.usercontact.count - 1{
if self.usercontact[i].monthorder == self.usercontact[j].monthorder && i != j{
if self.usercontact[i].dayorder > self.usercontact[j].dayorder{
let temp = self.usercontact[i]
self.usercontact[i] = self.usercontact[j]
self.usercontact[j] = temp
}
}
}
}
self.finaldata = self.usercontact + self.usercontactsort
}
self.tableview.reloadData()
}
catch {
print("Error \(error)")
}
}
}
})
session.resume()
}
- (BOOL)callWebService {
NSString *soapMessage = #"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:cgs=""http://www.cgsapi.com/""><soapenv:Header/><soapenv:Body><cgs:GetSystemStatus/></soapenv:Body></soapenv:Envelope>";
// SOAP request settings
NSURL *url = [NSURL URLWithString:#"http://www.cgsapi.com/CGSWebService.asmx"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSURLSession *session = [NSURLSession sharedSession];
NSError *error;
request.HTTPMethod = #"POST";
request.HTTPBody = [soapMessage dataUsingEncoding:NSUTF8StringEncoding];
[request addValue:#"www.cgsapi.com" forHTTPHeaderField:#"Host"];
[request addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request addValue:[NSString stringWithFormat:#"%i", soapMessage.length] forHTTPHeaderField:#"Content-Length"];
[request addValue:#"http://www.cgsapi.com/GetSystemStatus" forHTTPHeaderField:#"SOAPAction"];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"response: %#", response);
NSString *output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"output: %#", output);
if (error !=nil) {
NSLog(#"error: %i %#", error.code, error.description);
}
}];
[task resume];
return true;
}
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
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)
}
}
}