I'm trying to make api request with Alamofire. Data want to send with body. heare is what im doing.
let URL : String = "\(BaseUrl.sharedInstance.URL)\(EndPoint)"
do {
let options = NSJSONWritingOptions()
let data = try NSJSONSerialization.dataWithJSONObject(RequestData, options: options)
let jsons = NSString(data: data, encoding: NSUTF8StringEncoding)
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URL)!)
mutableURLRequest.HTTPMethod = "POST"
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
Alamofire.request(mutableURLRequest)
.response { request, response, data, error in
print(request)
let dataString = NSString(data: data!, encoding:NSUTF8StringEncoding)
print(dataString)
print(response)
print(error)
}
} catch {
print("JSON serialization failed: \(error)")
}
anyone have idea about it.
Alamofire.request(.POST, URLString, parameters: parameters, encoding: .JSON, headers: headerss).responseJSON
{
response in switch response.result
{
case .Success(let JSON):
let response = JSON as! NSDictionary
print (response);
onSuccess (response)
//example if there is an id
case .Failure(let error):
onFailure (error);
print("Request failed with error: \(error)")
}
}
Related
let header = [
"Content-Type":"application/json",
"X-Source":"iOS",
"Authorization":token]
let strURL = "ValidURL"
let manager = AFHTTPSessionManager()
let serializer = AFHTTPRequestSerializer()
for (_,dict) in header.enumerated() {
serializer.setValue("\(dict.value)", forHTTPHeaderField: "\(dict.key)")
}
manager.requestSerializer = serializer
let req = serializer.request(withMethod: "POST", urlString: strURL, parameters: params, error: nil)
manager.dataTask(with: req as URLRequest) { (response, data, error) in
print(error)
print(response)
print(data)
}
//No response from this method
Also, I tried:
var request = URLRequest(url: URL(string: strURL)!)
request.httpMethod = "POST"
for (_,dict) in header.enumerated() {
request.setValue("\(dict.value)", forHTTPHeaderField: "\(dict.key)")
}
request.httpBody = try! JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
manager.dataTask(with: request) { (response, data, error) in
print(error)
print(response)
print(data)
}
Even I have tried:
manager.post(strURL, parameters: params, progress: nil, success: { (sessionTask, respose) in
if let dict = respose as? Dictionary<String,Any> {
print(dict)
} else {
}
}) { (task, error) in
print(error)
}
//It Give me: failed: bad request (400)
There are two problems here
When you use a dataTask method, you get back a task object. You need to call resume() on it when you want the request to be sent.
Your errors indicate that your JSON body is incorrect. That is in your params object which probably does not match what the service is expecting.
I searched a lot and there's no clear instruction for sending POST request with "x-www-form-urlencoded" content-type.
i want to know how to do that and if you know how to do it with Alamofire it would be even better.
any help will be appreciated.
Hope you are searching for this one or give us more explanation in code so we get it easily:
let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]
let parameters = [
]
Alamofire.request("urlString", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case.success(let data):
print("success",data)
case.failure(let error):
print("Not Success",error)
self.view.makeToast(message: "Server Error!!")
}
}
I used below code in swift 4.2
guard let url = URL(string: "http://192.168.88.129:81/authenticate") else {
return
}
let user1 = username.text!
let pass = passwordfield.text!
print(user1)
print(pass)
let data : Data = "username=\(user1)&password=\(pass)&grant_type=password".data(using: .utf8)!
var request : URLRequest = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type");
request.setValue(NSLocalizedString("lang", comment: ""), forHTTPHeaderField:"Accept-Language");
request.httpBody = data
print("one called")
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// vs let session = URLSession.shared
// make the request
let task = session.dataTask(with: request, completionHandler: {
(data, response, error) in
if let error = error
{
print(error)
}
else if let response = response {
print("her in resposne")
}else if let data = data
{
print("here in data")
print(data)
}
DispatchQueue.main.async { // Correct
guard let responseData = data else {
print("Error: did not receive data")
return
}
let decoder = JSONDecoder()
print(String(data: responseData, encoding: .utf8))
do {
// let todo = try decoder.decode(T.self, from: responseData)
// NSAssertionHandler(.success(todo))
} catch {
print("error trying to convert data to JSON")
//print(error)
// NSAssertionHandler(.failure(error))
}
}
})
task.resume()
}
Try this following method using Alamofire
Alamofire.request("yourSide", method: .post, parameters: parameters, encoding: URLEncoding.default)
If it doesn't work, which is unlikely, use this following code
Alamofire.request("yourSide", method: .post, parameters: parameters, encoding: URLEncoding.httpBody)
code
let session = URLSession.shared
// prepare json data
let json: [String: Any] = ["email": "test_mobile#mysite.com"]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
let proceedURL = NSURL(string:"https://mysitename.herokuapp.com/api/users/isUser")
//let proceedURL = NSURL(string:"https://google.com")
let request = NSMutableURLRequest(url: proceedURL! as URL)
//HTTP Headers
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/www.inception.v1", forHTTPHeaderField: "Accept")
request.addValue("Authorization", forHTTPHeaderField: "Basic aW5jZXB0aW9uQGZ1cmRvOmljM=")
request.httpMethod = "POST"
//request.httpBody = jsonData
// insert json data to the request
request.httpBody = jsonData
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
// Print out response string
let responseString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
print("responseString = \(responseString!)")
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: AnyObject] {
print(json)
// handle json...
}
} catch let error {
print("error : " + error.localizedDescription)
}
})
task.resume()
error :
The data couldn’t be read because it isn’t in the correct format.
I am beginner in iphone app development, help me on it and give better suggestion for make network connection (like in android i am using Volley library )
Actual Response is :
{
"status": 1,
"http_status_code": 200,
"data": {
"email": "test_mobile#mysite.com",
"phone": "8090909000"
}
}
i am using same on Android and test in postmen.
// Print out response string
let responseString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
for upper code response is nothing
Using Alamofire.
let json: [String: Any] = ["email": "test_mobile#mysite.com"]
Alamofire.request(.POST, "https://mysitename.herokuapp.com/api/users/isUser" , parameters: json, encoding: .JSON).responseJSON {
Response in
switch Response.result {
case .Success(let _data):
let JsonData = JSON(_data)
print("JsonData : \(JsonData)")
//handle json
case .Failure(let _error):
print(_error)
let AlertBox = UIAlertController(title: "Connection Failed", message: "No Connection", preferredStyle: .Alert)
let ActionBox = UIAlertAction(title: "Ok" , style: .Default, handler: { _ in})
AlertBox.addAction(ActionBox)
self.presentViewController(AlertBox, animated: true, completion: nil)
}
let json: [String: Any] = ["email": "test_mobile#mysite.com"]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
// create post request
let url = URL(string: "http://httpbin.org/post")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
// insert json data to the request
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = responseJSON as? [String: Any] {
print(responseJSON)
}
}
task.resume()
I updated my project to Swift 3 and Alamofire 4. I was using custom Encoding, but it's changed to other encoding methods. I am not able to find the alternative/equivalent to this:
alamoFire.request(urlString, method: HTTPMethod.post, parameters: [:], encoding: .Custom({
(convertible, params) in
let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
let data = (body as NSString).data(using: String.Encoding.utf8)
mutableRequest.httpBody = data
return (mutableRequest, nil)
}), headers: headers()).responseJSON { (responseObject) -> Void in
switch responseObject.result {
case .success(let JSON):
success(responseObject: JSON)
case .failure(let error):
failure(error: responseObject)
}
}
I also tried by making URLRequest object and simple request its also giving me errors
var request = URLRequest(url: URL(string: urlString)!)
let data = (body as NSString).data(using: String.Encoding.utf8.rawValue)
request.httpBody = data
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers()
alamoFire.request(request).responseJSON { (responseObject) -> Void in
switch responseObject.result {
case .success(let JSON):
success(JSON)
case .failure(let error):
failure(responseObject, error)
}
}
Do point me in some direction, how to attach httpbody with the Alamofire 4
Try this method?
Alamofire.request(url, method: HTTPMethod.post, parameters: parameters, encoding: URLEncoding.httpBody, headers: nil).responseObject(completionHandler: { (response : DataResponse<T>) in
})
In Alamofire 4.0 you should use ParameterEncoding protocol. Here is an example, which makes any String UTF8 encodable.
extension String: ParameterEncoding {
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try urlRequest.asURLRequest()
request.httpBody = data(using: .utf8, allowLossyConversion: false)
return request
}
}
Alamofire.request("http://mywebsite.com/post-request", method: .post, parameters: [:], encoding: "myBody", headers: [:])
Hello i am using Alamofire but i am getting "Invalid JSON." in the response and i have used following code-
parametersV = ["username":amrit21#yopmail.com, "password":123456]
let headers = ["Content-Type": "application/json", "x-csrf-token":""]
Alamofire.request(.POST, "https://dev.staffingevolution.com/api/user/login", parameters: parametersV, headers: headers).responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
I Solved it
let parametersV = ["username":"amrit21#yopmail.com", "password":"123456"]
Alamofire.request(.POST, "https://dev.staffingevolution.com/api/user/login", parameters: parametersV, encoding: .JSON)
.responseJSON { response in
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
It was a problem was encoding you were not encoding your JSON request. use encoding: .JSON
Some times when in response there is not proper JSON then piece of code .responseJSON { response in throws exception and we can't see what type of response has been received. in such case we can print it to console before converting to .responseJSON { response in
Below is full example
public func deleteImage(_ photoId: Int) {
let requestURL = URL(string: APPURL.BASE_API_URL + "postApi/deletePostPhoto")!
let paramDict: [String: String] = ["photoId": String(photoId), "accessKey": APP_DELEGATE.loggedInUser.accessKey, "language":APP_DELEGATE.language.lowercased()]
Alamofire.upload(
multipartFormData: { multipartFormData in
for (key, value) in paramDict {
multipartFormData.append(value.data(using: .utf8)!, withName: key)
}
},
usingThreshold:UInt64.init(),
to: requestURL ,
method:.post,
headers:nil,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
// this is point where we can get actual response recieved from server, it may have some html , xml or anything
upload.responseData(completionHandler: { response in
print(response)
let responseData = String(data: response.data!, encoding: String.Encoding.utf8)
print("responseData=",responseData ?? "none")
})
// if there is proper JSON recieved it will be executed otherwise it will fall in failure
upload.responseJSON { response in
if((response.result.value) != nil) {
let swiftyJsonVar = JSON(response.result.value!)
print("response JSON: ",swiftyJsonVar)
}
else {
let error = response.error
print(error?.localizedDescription ?? "")
}
}
case .failure(let encodingError):
print(encodingError.localizedDescription)
}
})
}