Unable to POST a request in swift - ios

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}

Related

Issue with sending bearer token in http header using urlsession in swift 3

I am sending bearer token in header using urlsession but I always get the result as unauthorized. I have seen the server log. I am getting body in there but not header.
let key = UserDefaults.standard.object(forKey: "loginKey") as! String
print(key)
let url = NSURL(string: baseurl+"***")
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "GET"
request.addValue("Bearer " + key, forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request as URLRequest)
{(data,response,error) -> Void in
if error != nil
{
print(error?.localizedDescription as Any)
return
}
do
{
let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
print(json)
}
catch let error as NSError
{
print(error.localizedDescription)
}
}
task.resume()
I have also tried request.setValue("Bearer " + key, forHTTPHeaderField: "Authorization")
Try this :
var sessionConfig = URLSessionConfiguration.default
var authValue: String? = "Bearer \(key)"
sessionConfig.httpAdditionalHeaders = ["Authorization": authValue ?? <#default value#>]
var session = URLSession(configuration: sessionConfig, delegate: self as? URLSessionDelegate, delegateQueue: nil)

Getting an Authentication Failed error from server after hitting web service in Swift

The following below code is of hitting web service in swift by using NSURLSession .. I always get authentication failed message from server.Not able to get what is missing in request body.
let urlString:String = "\(BaseURL)"+"user_register.php?"
let deviceStr = "xyz"
let dictParam:NSDictionary = ["email":"\((emailTF?.text!)!)","username":"\((usernameTF?.text!)!)","password":"\((passwordTF?.text!)!)","device_key":deviceStr]
print(dictParam)
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
request.timeoutInterval = 60.0
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
// request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPMethod = "POST"
let dataToPost = try! NSJSONSerialization.dataWithJSONObject(dictParam, options: [])
request.HTTPBody = dataToPost
let task = session.dataTaskWithRequest(request) {
(
let data, let response, let error) in
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
print("error")
return
}
let response:AnyObject! = try! NSJSONSerialization.JSONObjectWithData(data!, options: [])
print(data!)
print(response)
}
task.resume()

sendSynchronousRequest is deprecated in ios 9 [duplicate]

This question already has an answer here:
Fixing NSURLConnection Deprecation from Swift 1.2 to 2.0
(1 answer)
Closed 7 years ago.
Xcode says that sendSynchronousRequest is now deprecated.
How should I replace it?
let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
let postLength:NSString = String( postData.length )
let 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("application/json", forHTTPHeaderField: "Accept")
var response: NSURLResponse?
var urlData: NSData?
do {
urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
} catch _ as NSError {
urlData = nil
} catch {
fatalError()
}
This is a working example,
You should use NSURLSession, with Request.
func testPost(sender: UIButton) {
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8080/iOSServer/ios/helloworld/swiftCalculator")!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
let d = "4"
let data = "x=4&y=\(d)"
request.HTTPBody = data.dataUsingEncoding(NSASCIIStringEncoding)
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let data = data{
print("data =\(data)")
}
if let response = response {
print("url = \(response.URL!)")
print("response = \(response)")
let httpResponse = response as! NSHTTPURLResponse
print("response code = \(httpResponse.statusCode)")
//if you response is json do the following
do{
let resultJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())
let arrayJSON = resultJSON as! NSArray
for value in arrayJSON{
let dicValue = value as! NSDictionary
for (key, value) in dicValue {
print("key = \(key)")
print("value = \(value)")
}
}
}catch _{
print("Received not-well-formatted JSON")
}
}
})
task.resume()
}
Notice it is not necessary to use the request. you can have a data task with URL, but I added the request because in your code, you have set some headers in the request.
Notice using the completionHandler which will be called when your server responses by http response.

How to send Json as parameter in url using swift

I am new in swift language. I looked at some questions for parsing Json in swift in here but my issue is alittle different from others.
when i write /cmd=login&params{'user':'username','password':'pass'} it returns correct data. how to resolve this in swift
I send username and password to url as json but
it retrieve error which means "invalid format "
Please help me.
Here is what i have tried:
var url:NSURL = NSURL(string: "http://<host>?cmd=login")!
//var session = NSURLSession.sharedSession()
var responseError: NSError?
var request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
// var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
var response: NSURLResponse?
request.HTTPMethod = "POST"
let jsonString = "params={\"user\":\"username\",\"password\":\"pass\"}"
request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion:true)
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
// send the request
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &responseError)
// look at the response
if let httpResponse = response as? NSHTTPURLResponse {
println("HTTP response: \(httpResponse.statusCode)")
} else {
println("No HTTP response")
}
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
if error != nil {
println("error=\(error)")
return
}
println("****response= \(response)")
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("**** response =\(responseString)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers , error: &err) as? NSDictionary
}
task.resume()
Assuming based on your question that the format the server is expecting is something like this:
http://<host>?cmd=login&params=<JSON object>
You would need to first URL-encode the JSON object before appending it to the query string to eliminate any illegal characters.
You can do something like this:
let jsonString = "{\"user\":\"username\",\"password\":\"pass\"}"
let urlEncoadedJson = jsonString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
let url = NSURL(string:"http://<host>?cmd=login&params=\(urlEncoadedJson)")
Let's say url is
https://example.com/example.php?Name=abc&data={"class":"625","subject":"english"}
in Swift 4
let abc = "abc"
let class = "625"
let subject = "english"
let baseurl = "https://example.com/example.php?"
let myurlwithparams = "Name=\(abc)" + "&data=" +
"{\"class\":\"\(class)\",\"subject\":\"\(subject)\"}"
let encoded =
myurlwithparams.addingPercentEncoding(withAllowedCharacters:
.urlFragmentAllowed)
let encodedurl = URL(string: encoded!)
var request = URLRequest(url: encodedurl!)
request.httpMethod = "GET"
I don't think you need to encode your JSON the way you're doing it. Below should work.
let jsonString = "params={\"user\":\"username\",\"password\":\"pass\"}"
var url:NSURL = NSURL(string: "http://<host>?cmd=login&?\(jsonString)")!
//var session = NSURLSession.sharedSession()
var responseError: NSError?
var request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
// var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
var response: NSURLResponse?
request.HTTPMethod = "POST"
You json string is not valid, it should be like:
let jsonString = "{\"user\":\"username\",\"password\":\"pass\"}"
As for the request, I think GET it what you really need:
var urlString = "http://<host>" // Only the host
let payload = "?cmd=login&params=" + jsonString // params goes here
urlString += payload
var url:NSURL = NSURL(string: urlString)!
// ...
request.HTTPMethod = "GET"

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