I am trying to make a HTTP Post using alamofire, below is my code:
#IBAction func loginUserBtn(_ sender: Any) {
let urlAddress = "http://xx.xx.xx.xx:xx/xx/xx/xx/login"
let pass = Array(userPassword.text!)
let username = userEmail.text!
let params : [String: Any] = ["username": username, "pwd": pass]
print(params)
let headers: HTTPHeaders = [
"Accept": "application/json",
"Content-Type": "application/json"
]
Alamofire.request(urlAddress, method: .post, parameters: params, encoding: URLEncoding.default, headers: headers).responseJSON{
responds in
if responds.result.isSuccess{
print("Succesfull")
let LoginJSON : JSON = JSON(responds.result.value!)
//self.updateWeatheData(json: weatherJSON)
print(LoginJSON)
}
else{
print("Error \(String(describing: responds.result.error))")
}
}
}
This is the error I'm getting but if I change responseJSON to responseString I get a success, but the server is rejecting my data.
Here is my error message:
Error Optional(Alamofire.AFError.responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})))
encoding: URLEncoding.default
I see what you have header of content-type is JSON, but Encoding field inform in what type your params. Try this:
encoding: JSONEncoding.default
Related
In using swift 2.2, while using NSURLSession I am not getting the Response. What am I doing wrong?
I have to pass parameters and header in POST request.
func API() {
let userName:String! = "uname"
let password:String! = "password"
let request = NSMutableURLRequest(URL: NSURL(string: URL)!)
request.HTTPMethod = "POST"
let data = try! NSJSONSerialization.dataWithJSONObject(parameter, options:[])
let json = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
request.HTTPBody = json.dataUsingEncoding(NSUTF8StringEncoding)
request.allHTTPHeaderFields = ["key":"value"]
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
}
Result is:
responseString = Optional("")
Did you call this service on any REST client like Postman ? if yes and get response so try replace this line
request.allHTTPHeaderFields = ["key":"value"]
with this
request.setValue("value",forHTTPHeaderField:"Key")
and set all values
This question already has answers here:
Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)
(14 answers)
Closed 6 years ago.
I have a swift 2.3 project I just updated to swift 3.0 and the following code broke.
let task = URLSession.shared.dataTask(with: request, completionHandler: {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = NSString(data: data!, encoding: String.Encoding.utf8)
print("responseString = \(responseString)")
})
task.resume()
I am unaware how to fix it
You can get that error if the request is a NSURLRequest rather than a URLRequest.
let url = URL(string: urlString)!
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
Or, if you're mutating the URLRequest, use var:
let url = URL(string: urlString)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = ...
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
Also, note, I've replaced NSString with String.
I'm trying to perform a GET request but am getting the following two errors:
use of unresolved identifier 'self'
and
Expected declaration
This is my affected code
let credentialData = "\(self._username):\(self._password)".dataUsingEncoding(NSUTF8StringEncoding)!
let base64Credentials = credentialData.base64EncodedStringWithOptions([])
let headers = ["Authorization": "Basic \(base64Credentials)"]
Alamofire.request(.GET, "http://gemcave.pythonanywhere.com/api/order\(self._username)/\(self._password)", headers: headers)
.responseJSON { response in
debugPrint(response)
}
You need to put your code into some method like this:
func networkConfiguration() {
let credentialData = "\(self._username):\(self._password)".dataUsingEncoding(NSUTF8StringEncoding)!
let base64Credentials = credentialData.base64EncodedStringWithOptions([])
let headers = ["Authorization": "Basic \(base64Credentials)"]
Alamofire.request(.GET, "http://gemcave.pythonanywhere.com/api/order\(self._username)/\(self._password)", headers: headers)
.responseJSON { response in
debugPrint(response)
}
}
i need to send the json request parameters to the server using nsurl session in swift2.0. i don't know how to create the json request params.i created the params like this
let jsonObj = ["Username":"Admin", "Password":"123","DeviceId":"87878"]
// print("Params are \(jsonObj)")
//request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(jsonObj, options: [])
// or if you think the conversion might actually fail (which is unlikely if you built `params` yourself)
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(jsonObj, options:.PrettyPrinted)
} catch {
print(error)
}
but its not ping to the method body so i am getting the failure response
Try the below code.
let parameters = ["Username":"Admin", "Password":"123","DeviceId":"87878"] as Dictionary<String, String>
let request = NSMutableURLRequest(URL: NSURL(string:YOURURL)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
//Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])
let task = session.dataTaskWithRequest(request) { data, response, error in
guard data != nil else {
print("no data found: \(error)")
return
}
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print("Response: \(json)")
} else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
print("Error could not parse JSON: \(jsonStr)")
}
} catch let parseError {
print(parseError)// Log the error thrown by `JSONObjectWithData`
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
}
}
task.resume()
Hope it works for you!!
New to Swift and trying to write a login screen for my app.
My controller:
#IBAction func loginButton(sender: UIButton) {
let emailAddress = emailTextField.text
let password = passwordTextField.text
let api = Api()
api.authenticate(emailAddress!, password: password!)
}
Api class:
class Api {
func authenticate(username: String, password: String) -> Bool {
var params = [String: String]()
params["username"] = username
params["password"] = password
params["grant_type"] = "password"
var headers = [String: String]()
headers["Content-Type"] = "application/x-www-form-urlencoded"
post("authenticate", params: params, headers: headers) {data, response in
// do something
}
}
func post(location: String, params: [String: String], headers: [String: String], callback: ((data: NSString!, response: NSHTTPURLResponse) -> Void)) {
let request = NSMutableURLRequest()
let session = NSURLSession.sharedSession()
request.URL = NSURL(string: Configuration.apiBaseUrl + location)
request.HTTPMethod = "POST"
request.HTTPBody = NSString(string: getPostBody(params)).dataUsingEncoding(NSUTF8StringEncoding)
request.addValue("Basic " + Configuration.apiAuthorization, forHTTPHeaderField: "Authorization")
for (key, value) in headers {
request.addValue(value, forHTTPHeaderField: key)
}
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
let data = NSString(data: data!, encoding: NSUTF8StringEncoding)
let httpResponse = response as! NSHTTPURLResponse
callback(data: data, response: httpResponse)
return
})
task.resume()
}
}
As I plan to add more API methods after authentication, I want generic POST/PUT/GET/DELETE methods. I am trying to understand how I can best set up the callbacks in Swift so the post call in the authenticate method can return true/false and show like a dialog on the UI thread. Returning a boolean in the post call in the authenticate method is not allowed now, because it expects Void.
I am familiar with callbacks in nodejs and trying to grasp this now. Any hints what the best approach would be?