I'm trying to make a GET request with Alamofire in Swift. I need to set the following headers:
Content-Type: application/json
Accept: application/json
I could hack around it and do it directly specifying the headers for the request, but I want to do it with ParameterEncoding, as is suggested in the library. So far I have this:
Alamofire.request(.GET, url, encoding: .JSON)
.validate()
.responseJSON { (req, res, json, error) in
if (error != nil) {
NSLog("Error: \(error)")
println(req)
println(res)
} else {
NSLog("Success: \(url)")
var json = JSON(json!)
}
}
Content-Type is set, but not Accept. How can I do this properly?
I ended up using URLRequestConvertible https://github.com/Alamofire/Alamofire#urlrequestconvertible
enum Router: URLRequestConvertible {
static let baseUrlString = "someUrl"
case Get(url: String)
var URLRequest: NSMutableURLRequest {
let path: String = {
switch self {
case .Get(let url):
return "/\(url)"
}
}()
let URL = NSURL(string: Router.baseUrlString)!
let URLRequest = NSMutableURLRequest(URL:
URL.URLByAppendingPathComponent(path))
// set header fields
URLRequest.setValue("application/json",
forHTTPHeaderField: "Content-Type")
URLRequest.setValue("application/json",
forHTTPHeaderField: "Accept")
return URLRequest.0
}
}
And then just:
Alamofire.request(Router.Get(url: ""))
.validate()
.responseJSON { (req, res, json, error) in
if (error != nil) {
NSLog("Error: \(error)")
println(req)
println(res)
} else {
NSLog("Success")
var json = JSON(json!)
NSLog("\(json)")
}
}
Another way to do it is to specify it for the whole session, check #David's comment above:
Alamofire.Manager.sharedInstance.session.configuration
.HTTPAdditionalHeaders?.updateValue("application/json",
forKey: "Accept")
Example directly from Alamofire github page:
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.response { (_, _, _, error) in
println(error)
}
In your case add what you want:
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.validate(Accept: ["application/json"])
.response { (_, _, _, error) in
println(error)
}
Simple way to use get method with query map and response type json
var parameters: [String:Any] = [
"id": "3"
]
var headers: HTTPHeaders = [
"Content-Type":"application/json",
"Accept": "application/json"
]
Alamofire.request(url, method: .get,
parameters: parameters,
encoding: URLEncoding.queryString,headers:headers)
.validate(statusCode: 200..<300)
.responseData { response in
switch response.result {
case .success(let value):
case .failure(let error):
}
Alamofire.request(url, method: .post, parameters:parameters, encoding: JSONEncoding.default).responseJSON { response in
...
}
it's work
Try this:
URLRequest.setValue("application/json",
forHTTPHeaderField: "Content-Type")
URLRequest.setValue("application/json",
forHTTPHeaderField: "Accept")
Related
I'm doing a POST call to server but Alamofire always send the body as a JSON and not as a Form URL Encoded, I do know that in oder to encode the body I have to insert data(using: .utf8, allowLossyConversion: false), but I don't know where.
How can I fix my code?
This is my actual code:
func asURLRequest() throws -> URLRequest {
let url = try DBank.StagingServer.baseUrl.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
// HTTP Method
urlRequest.httpMethod = method.rawValue
// Common Headers
headers.forEach { (field, value) in
urlRequest.setValue(value, forHTTPHeaderField: field)
}
// Parameters
if let parameters = parameters {
do {
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
}
I'm guessing you have response handler like below:
Alamofire.request(url, method: .post, parameters: params, encoding: URLEncoding(destination: .queryString), headers: headers)
.validate(statusCode: 200..<300)
.responseString { response in
//response.result.value will contain http response from your post call
}
With the result from this response you would set:
UserDefaults.standard.set("<result>", forKey: "<token>")
This question already has answers here:
Send POST parameters with MultipartFormData using Alamofire, in iOS Swift
(13 answers)
Closed 5 years ago.
I want to make a request wit Alamofire like this:
postman request
As you can see, i have a parameter called "data" and its value is a Json,
How can i do that using Alamofire?
I have tried with parameters, but doesnt wotk
Alamofire.request(urlservice, method: .post, parameters: ["data": parameters], encoding: JSONEncoding.default, headers: nil).responseJSON { response in
Any suggestions?
UPDATE
Here is my code
var arrayProducts = [[String: String]]()
let product: [String: String] = ["qty": self.txtQty.text!, "precio": self.productPrice, "product_id": self.productId]
arrayProducts.append(product)
let parameters = [
"products": arrayProducts,
"address": self.userInfo["userAddress"]!,
"latitude": "6.157738",
"longitude": "-75.6144665",
"id": 1,
"name": self.userInfo["userName"]!,
"cellphone": self.userInfo["userPhone"]!,
"emei": "23456resdfty"
] as [String : Any]
Alamofire.request(urlservice, method: .post, parameters: ["data": parameters], encoding: JSONEncoding.default, headers: nil).responseJSON { response in
when you have an Any Data as paremeter, you should sent the URLRequest to Alamofire, it supports Any as body
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try! JSONSerialization.data(withJSONObject: parameters, options: [])
Alamofire.request(request)
.responseString { (response) in
// to do anything
}
Here is an example 4 you, the CURL statement an example of what it is doing.
Note token referenced here is a shared secret, obviously not stuff to post to SO :) bags of print statements in here so that you can see what going on/wrong :)
func files_download(sourcePath: String) {
// curl -X POST https://content.dropboxapi.com/2/files/download
// --header "Authorization: Bearer ab-XXX"
// --header "Dropbox-API-Arg: {\"path\": \"/acme101/acme1/acme.png\"}"
var headers:HTTPHeaders!
let subPart: Dictionary = ["path":sourcePath]
do {
let data = try JSONSerialization.data(withJSONObject: subPart, options: [])
let dataString = String(data: data, encoding: .utf8)
headers = ["Authorization": "Bearer " + token, "Dropbox-API-Arg": dataString!]
} catch {
print("Oh fudge")
}
Alamofire.request("https://content.dropboxapi.com/2/files/download", method: .post, encoding: JSONEncoding.init(options: []), headers: headers).responseData(completionHandler: {feedback in
guard feedback.result.value != nil else {
print("Error: did not receive data", //rint("request \(request) feedback \(feedback)"))
return
}
guard feedback.result.error == nil else {
print("error calling POST on list_folder")
print(feedback.result.error)
return
}
if let JSON = feedback.result.value {
print("JSON: \(JSON)")
let dataString = String(data: JSON, encoding: .utf8)
print("JSON: \(JSON) \(String(describing: dataString))")
}
if let IMAGE = feedback.result.value {
print("downloaded \(sourcePath) \(sharedDataAccess.currentSN)")
sharedDataAccess.fnData(index2seek: sharedDataAccess.currentSN, fnData: feedback.result.value! as Data)
NotificationCenter.default.post(name: Notification.Name("previewPane"), object: nil, userInfo: nil)
}
})
}
This question already has answers here:
POST request with a simple string in body with Alamofire
(12 answers)
Closed 5 years ago.
I am new in iOS development . I am using alamofire in swift 3 . How can i send post request in alamofire . It also gives extra argument in method.
Thanks in advance
First of all you add almofire library into your project then import almofire into your ViewController then below method apply in your button action.
func webServiceLogin(isFbLogin:Bool,email:String,password:String)
{
var parameters:[String:String]?
parameters = ["hash":email as String,"key":password ]
Alamofire.request("your url", method: .post, parameters: parameters,encoding: URLEncoding.default, headers: nil).responseJSON {
response in
hideHud(self.view)
switch response.result {
case .success:
if let dictSuccess:NSDictionary = response.value as! NSDictionary?
{
}
break
case .failure(let error):
Alert.showAlertWithTitle(strTitle: appTitle, strMessage: error.localizedDescription, onView: self)
print(response)
print(error)
}
}
}
Use like bellow and pass your parameter which you want to send in server. Better you write an Network layer class using this then It will be reusable throughout the whole application.
static func serverRequest(urlString: URL?, Parameter:NSDictionary?, completion: #escaping (_ serverResponse: AnyObject?,_ error:NSError?)->()){
// let parameters: Parameters = ["foo": "bar"]
//let headers = ["Authorization": "123456"]
Alamofire.request(urlString!, parameters:nil, headers: nil).responseJSON { response in
if(response.result.value != nil){
let serverResponse = JSON(response.result.value!)
//print("Array value is \(serverResponse.arrayValue)")
completion(serverResponse as AnyObject?, nil)
}
else{
completion(nil, response.result.error as NSError?)
}
}
}
You can use alamofire manager
var alamoFireManager = Alamofire.SessionManager
let request = URLRequest(url:_yourULR)
request.HTTPMethod = requestMethod.rawValue
request.timeoutInterval = //set yours
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("gzip", forHTTPHeaderField: "Accept-Encoding")
request.HTTPBody = "you_bodydataSTring".dataUsingEncoding(String.Ecoding.utf8)
alamoFireManager.request(request)
.validate()
.responseString { (response) -> Void in
let datastring = NSString(data:response.data!, encoding: String.Ecoding.utf8)
switch response.result {
case .Success:
if response.response?.statusCode == 200 {
//code for success
}else{
//others
}
case .Failure(let error):
//request failed
}
}
}
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: [:])
My goal is to create a simple function where I pass in a url and it returns me JSON. I have looked around and found little examples of where a completion handler is implemented with Alamofire.
I am also using Swifty Json to help parse it out.
How do I turn what I have here to a function where it returns my Json.
func request() {
Alamofire.request(.GET, API_END_POINT)
.responseJSON {
response in
// swiftyJsonVar is what I would like this function to return.
let swiftyJsonVar = JSON(response.result.value!)
}
}
Swift 3+ and Alamofire 4+
// Call function
myFunction("bodrum") { response in
print(response["yourParameter"].stringValue)
}
// POST
func myFunction(_ cityName:String, completion: #escaping (JSON) -> ()) {
let token = "token"
let parameters = ["city" : cityName]
let headers = ["Authorization": "token"]
let url = URL(string: "url")!
let reqUrl = URLRequest(url: url)
Alamofire.request(reqUrl, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: headers)
.validate()
.responseJSON { response in
switch response.result {
case .Success:
let jsonData = JSON(data: response.data!)
completion(jsonData)
case .Failure(let error):
MExceptionManager.handleNetworkErrors(error)
completion(JSON(data: NSData()))
}
}
}
Swift 2 and Alamofire 3+
// POST
func myFunction(cityName:String, completion : (JSON) -> ()) {
Alamofire.request(.POST, "url", parameters: ["city" : cityName], encoding: ParameterEncoding.JSON, headers: ["Authorization": "token"])
.validate()
.responseJSON { response in
switch response.result {
case .Success:
let jsonData = JSON(data: response.data!)
completion(jsonData)
case .Failure(let error):
MExceptionManager.handleNetworkErrors(error)
completion(JSON(data: NSData()))
}
}
}
// GET
func myFunction(cityName:String, completion : (JSON) -> ()) {
Alamofire.request(.GET, "url", parameters: ["param1" : cityName], headers: ["Authorization": "token"])
.validate()
.responseJSON { response in
switch response.result {
case .Success:
let jsonData = JSON(data: response.data!)
completion(jsonData)
case .Failure(let error):
MExceptionManager.handleNetworkErrors(error)
completion(JSON(data: NSData()))
}
}
}
// Call function
myFunction("bodrum") { response in
print(response["yourParameter"].stringValue)
}