How can i use alamofire for post api [duplicate] - ios

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
}
}
}

Related

Alamofire 4 Swift 3 GET request with parameters

I'm building a network stack using Alamofire 4 and Swift 3. Following the Alamofire guidelines I've created a router for the endpoints of the services. I'm currently using the free API of OpenWeatherMap but I'm finding problems in order to create a get request.
That's the url needed: http://api.openweathermap.org/data/2.5/weather?q=Rome&APPID=MY_API_KEY. Pasted on a browser, and using a real API Key it works and gives me back my nice json full of info about the weather in the given location.
On my App I can insert the parameters as Dictionary but I cannot find a way to append the api key at the end of the url.
That's my enum router:
enum OWARouter: URLRequestConvertible {
case byCityName(parameters: Parameters)
// MARK: Url
static let baseURLString = "http://api.openweathermap.org"
static let apiKey = "MY_APY_KEY"
static let pathApiKey = "&APPID=\(apiKey)"
var method: HTTPMethod {
switch self {
case .byCityName:
return .get
}
}
var path: String {
switch self {
case .byCityName:
return "/data/2.5/weather"
}
}
// MARK: URLRequestConvertible
func asURLRequest() throws -> URLRequest {
let url = try OWARouter.baseURLString.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
switch self {
case .byCityName(let parameters):
urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters)
print((urlRequest.url)!)
}
urlRequest.httpMethod = method.rawValue
return urlRequest
}
}
When I log my (urlRequest.url)! I have this: http://api.openweathermap.org/data/2.5/weather?q=Rome but I cannot find a way to add the apiKey.
What am I doing wrong?
I've also made an ugly test adding this code after the print:
var urlRequest2 = URLRequest(url: (urlRequest.url)!.appendingPathComponent(OWARouter.pathApiKey))
print("URL2: \(urlRequest2)")
And the log is URL2: http://api.openweathermap.org/data/2.5/weather/&APPID=My_API_KEY?q=Rome
How come the api key is in the middle?
If you need this is the simple request code:
Alamofire.request(OWARouter.byCityName(parameters: ["q":"Rome"])).responseJSON { response in
print(response.request)
print(response.response)
print(response.data)
print(response.result)
debugPrint(response)
if let JSON = response.result.value {
print("json: \(JSON)")
}
}
Another question...
If I use as parameters ["q":"Rome, IT"], my output url is: http://api.openweathermap.org/data/2.5/weather?q=Rome%2CIT
How to keep the comma?
Thank you!
Swift - 5 Alamofire 5.0 Updated Code (just Change AF.request Method according to your requirement you can add Parameters headers and intercepter as well )
Alamofire.request(url, method: .get, encoding: JSONEncoding.default)
.responseJSON { response in
switch response.result {
case .success(let json):
print(json)
DispatchQueue.main.async {
// handle your code
}
case .failure(let error):
print(error)
}
}
Used below lines of code:
func getRequestAPICall(parameters_name: String) {
let todosEndpoint: String = "your_server_url" + "parameterName=\(parameters_name)"
Alamofire.request(todosEndpoint, method: .get, encoding: JSONEncoding.default)
.responseJSON { response in
debugPrint(response)
if let data = response.result.value{
// Response type-1
if (data as? [[String : AnyObject]]) != nil{
print("data_1: \(data)")
}
// Response type-2
if (data as? [String : AnyObject]) != nil{
print("data_2: \(data)")
}
}
}
}
func AlamofireGetCode()
{
var url:String!
url = "https://jsonplaceholder.typicode.com/comments"
Alamofire.request(url, method: .get, encoding: JSONEncoding.default)
.responseJSON { response in
switch response.result{
case .success(let json):
print(json)
DispatchQueue.main.async {
print(json)
self.mainarray = json as? NSArray
print(self.mainarray as Any)
self.mytableviewreload.reloadData()
}
case .failure(let error):
print(error)
}
}
}
I've found a solution... the Api Key is simply a parameter to send to the request. So the code to change is not in the router but in the request function:
Alamofire.request(OWARouter.byCityName(parameters: ["q":"Rome","APPID":"MY_API_KEY"])).responseJSON { response in
print(response.request)
//print(response.response)
//print(response.data)
//print(response.result)
//debugPrint(response)
if let JSON = response.result.value {
print("json: \(JSON)")
}
}
EDIT: the comma issue do not gives me any problem now. Thank you.
Swift 5+
Use AF.request
let todosEndpoint: String = "https://jsonplaceholder.typicode.com/todos/1"
let request = AF.request(todosEndpoint)
request.responseJSON { (data) in
print("Response", data)
}
**//
Fist in third party liabrary, install pod 'Alamofire'
Using Alamofire get json data
import UIKit
import Alamofire
class APIWRAPPER: NSObject {
static let instance = APIWRAPPER()
func LoginAPI(Uname : String , Password : String) {
let requestString =
"http://************php/v1/sign-in"
let params = ["user_name": Uname,
"password": Password]
Alamofire.request(requestString,method: .get, parameters: params, encoding: JSONEncoding.prettyPrinted, headers: [:]).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if response.result.value != nil
{
print("response : \(response.result.value!)")
}
else
{
print("Error")
}
break
case .failure(_):
print("Failure : \(response.result.error!)")
break
}
}
}
}

POST request with data in body with Alamofire 4

how is it possible to send a POST request with a data in the HTTP body with Alamofire 4? I used custom encoding at swift 2.3 it was working good. I converted my code swift 3 and I tried to paramater encoding but not working. This code :
public struct MyCustomEncoding : ParameterEncoding {
private let data: Data
init(data: Data) {
self.data = data
}
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
do {
urlRequest.httpBody = data
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
return urlRequest
}
and Alamofire request :
let enco : ParameterEncoding = MyCustomEncoding(data: ajsonData)
Alamofire.request(urlString, method: .post , parameters: [:], encoding: enco , headers: headers).validate()
.responseJSON { response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}
You need to send request like below in swift 3
let urlString = "https://httpbin.org/get"
Alamofire.request(urlString, method: .post, parameters: ["foo": "bar"],encoding: JSONEncoding.default, headers: nil).responseJSON {
response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}
Swift 5 with Alamofire 5:
AF.request(URL.init(string: url)!, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
print(response.result)
switch response.result {
case .success(_):
if let json = response.value
{
successHandler((json as! [String:AnyObject]))
}
break
case .failure(let error):
failureHandler([error as Error])
break
}
}
Alamofire using post method
import UIKit
import Alamofire
class ViewController: UIViewController {
let parameters = [
"username": "foo",
"password": "123456"
]
let url = "https://httpbin.org/post"
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: [:]).responseJSON {
response in
switch (response.result) {
case .success:
print(response)
break
case .failure:
print(Error.self)
}
}
}
This will work better in Swift 4.
let url = "yourlink.php". // This will be your link
let parameters: Parameters = ["User_type": type, "User_name": name, "User_email": email, "User_contact": contact, "User_password": password, "from_referral": referral] //This will be your parameter
Alamofire.request(url, method: .post, parameters: parameters).responseJSON { response in
print(response)
}
Please find the code below
**
pod 'Alamofire', '~> 5.4'
**
**
pod 'ObjectMapper', '~> 4.2'
**
**
pod 'SwiftyJSON'
**
pod 'TPKeyboardAvoiding'
Use Model
import ObjectMapper
class LoginModel : Mappable{
var status : String?
var data : [DataModel]?
var message : String?
required init?(map: Map) {
}
func mapping(map: Map) {
status <- map["status"]
data <- map["data"]
message <- map["message"]
}
}
class DataModel : Mappable{
var access_token : String?
var isvideo : String?
required init?(map: Map) {
}
func mapping(map: Map) {
access_token <- map["access_token"]
isvideo <- map["isvideo"]
}
}
Call API
HTTPNetwork().getHTTPData("", parameters: LoginParameter, completion: {(successresponse) -> Void in
if let res = successresponse{
print("sucess token \(res["message"].string!)")
if let myuser = Mapper<DataModel>().map(JSONString: res["data"].rawString()!){
print("access_token \(myuser.access_token)")
}
}
}, error: {(errorresponse)-> Void in
if let res = errorresponse{
print("Error response token \(res)")
}
})
public func getHTTPData(_ request: String, parameters : Parameters?, completion: #escaping ( JSON?) -> Void, error: #escaping ( JSON?) -> Void){
AF.request(URL.init(string: "url")!, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: ["Content-Type":"application/json"]).responseJSON { (response) in
print(response.result)
switch response.result{
case .success:
if let json = response.value as? [String : Any]{
if let output:JSON = JSON(response.value!){
if json["isSuccess"] as? Int == 1{
completion(output)
}else{
error(output)
}
}
}else{
completion(nil)
}
case .failure:
completion(nil)
}
}
}
Alamofire for GET and POST method using Alamofire
1.Create a file named "GlobalMethod" for multiple use
import Alamofire
class GlobalMethod: NSObject {
static let objGlobalMethod = GlobalMethod()
func ServiceMethod(url:String, method:String, controller:UIViewController, parameters:Parameters, completion: #escaping (_ result: DataResponse<Any>) -> Void) {
var headers = Alamofire.SessionManager.defaultHTTPHeaders
headers["HeaderKey"] = "HeaderKey"
if method == "POST" {
methodType = .post
param = parameters
}
else {
methodType = .get
}
Alamofire.request(url, method: methodType, parameters: param, encoding: JSONEncoding.default, headers:headers
).responseJSON
{ response in
completion(response)
}
}
}
In the View Controller call "ServiceMethod" created in GlobalMethod by sending values to call API Service
let urlPath = "URL STRING"
let methodType = "GET" or "POST" //as you want
let params:[String:String] = ["Key":"Value"]
GlobalMethod.objGlobalMethod.ServiceMethod(url:urlPath, method:methodType, controller:self, parameters:params)
{
response in
if response.result.value == nil {
print("No response")
return
}
else {
let responseData = response.result.value as! NSDictionary
print(responseData)
}
}

Alamofire 4 Swift 3 ParameterEncoding Custom

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: [:])

Swift 2.0 Alamofire Completion Handler Return Json

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)
}

Alamofire Accept and Content-Type JSON

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")

Resources