Related
I have a simple procedure, which I used in my earlier version (Swift 4). I have now updated to the new version (Swift 5, Alamofire 5.0.0-rc.2), as I am still beginner I got problems with this. Some code parts I could already rewrite.
let headers: HTTPHeaders = [
"SubscriptionKey": SubscriptionKey,
"Host": HostName
]
AF.request(URL(string: userInfoUrl)!, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers)
.validate()
.responseJSON { response in
guard response.result.isSuccess else {
log.error("Error requesting user ID: \(String(describing: response.result.error))")
completion(false, nil)
return
}
guard let json = response.result.value as? [String: Any], let userId = json["userId"] as? String else {
log.error("Malformed result from API call.")
completion(false, nil)
return
}
response.result.isSuccess is not possible. How can I reuse this part?
Error: Value of type 'Result' has no member 'isSuccess'
As a possible solution, I will test the above solution.
AF.request(URL(string: userInfoUrl)!, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers)
.validate()
.responseJSON { response in
switch response.result{
case .success(let value):
//succcess, do anything
case .failure(let error):
log.error("Error requesting user ID: \(String(describing: response.error))")
completion(false, nil)
return
}
Result is containing .success or .failure case.
So you should treat isSuccess like this
switch response.result {
case .success(let value):
//success, do anything
case .failure(let error):
//failure
}
I am using like this, but in this case, I need to call API with parameters and Body. Please help me. Thanks in advance.
Alamofire.request(postUrl, method: .post, parameters: params, encoding: CustomPostEncoding(), headers: nil).validate().responseJSON{ response in
switch response.result
{
case .success:
MBProgressHUD.hide(for: self.view, animated: true)
if let val = response.result.value
{
let json = JSON(val)
print(json)
}
case .failure(let error):
print(error)
}
}
var url = "http://..."
let _headers : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]
let params : Parameters = ["grant_type":"password","username":"mail","password":"pass"]
let url = NSURL(string:"url" as String)
request(url, method: .post, parameters: params, encoding: URLEncoding.httpBody , headers: _headers).responseJSON(completionHandler: {
response in response
let jsonResponse = response.result.value as! NSDictionary
if jsonResponse["access_token"] != nil
{
access_token = String(describing: jsonResponse["accesstoken"]!)
}
})
Refrence :- POST request with a simple string in body with Alamofire
use your parameters instead of class_id ,and time.
func listOfClassesData(url: String,class_id: String,time: String,redClassesData : [String: Any] ,completionHandler:#escaping (Bool) -> ()){
let Auth_header = ["Authorization" : "Bearer "+getBearerToken()]
let paameters:Parameters = [
"class_id" : class_id,
"time" :time,
]
print(url,Auth_header)
Alamofire.request(url, method: .post, parameters: paameters, encoding: JSONEncoding.default, headers: Auth_header)
.responseJSON { response in
print(response)
switch response.result{
case .success:
let statusCode: Int = (response.response?.statusCode)!
switch statusCode{
case 200:
if let json = response.result.value{
completionHandler(true)
}
break
default:
completionHandler(false)
break
}
break
case .failure:
completionHandler(false)
break
}
}
}
let url = "your api url"
let param = ["user":"user#test.com","pass":"12345"]
Alamofire.request(url, method: .post , parameters: param)
.validate()
.responseJSON {
response in
switch response.result{
case .success:
var jsonResult = [String:AnyObject]()
do
{
//Get response successfully of api
jsonResult = try JSONSerialization.jsonObject(with: response.data!, options: []) as! [String:AnyObject]
print(jsonResult)
}
catch let error as NSError {
//get error if there is any problem in response of api.
print("--->",error)
}
case .failure(let error):
//get error if there is any problem while calling api.
print("---->",error)
}
}
I have migrated my project to Swift 3 (and updated Alamofire to latest Swift 3 version with pod 'Alamofire', '~> 4.0' in the Podfile).
I now get an "Extra argument in call" error on every Alamofire.request. Eg:
let patientIdUrl = baseUrl + nextPatientIdUrl
Alamofire.request(.POST, patientIdUrl, parameters: nil, headers: nil, encoding: .JSON)
Can anybody tell me why ?
According to Alamofire documentation for version 4.0.0 URL request with HTTP method would be followings:
Alamofire.request("https://httpbin.org/get") // method defaults to `.get`
Alamofire.request("https://httpbin.org/post", method: .post)
Alamofire.request("https://httpbin.org/put", method: .put)
Alamofire.request("https://httpbin.org/delete", method: .delete)
So your url request will be:
Alamofire.request(patientIdUrl, method: .post, parameters: nil, encoding: JSONEncoding.default, headers: nil)
and a sample request will be:
Alamofire.request(url, method: .post, parameters: param, encoding: JSONEncoding.default, headers: [AUTH_TOKEN_KEY : AUTH_TOKEN])
.responseJSON { response in
print(response.request as Any) // original URL request
print(response.response as Any) // URL response
print(response.result.value as Any) // result of response serialization
}
Hope this helps!
This one worked for me. No need to remove encoding parameter
Update for Swift 5.x
Alamofire uses the Result type introduced in Swift 5.Also Alamofire.request has been changed to AF.request which will now read their switch response.result value with .success and .failure
AF.request("https://yourServiceURL.com", method: .get, parameters: [:], encoding: URLEncoding.default, headers: ["":""]).responseJSON { (response) in
switch response.result {
case let .success(value):
print(value)
case let .failure(error):
print(error)
}
}
Swift 3.x / 4.x
Alamofire.request("https://yourServiceURL.com", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if let data = response.result.value{
print(response.result.value)
}
break
case .failure(_):
print(response.result.error)
break
}
}
and make sure that the parameters are of type
[String:Any]?
In case of Get
Alamofire.request("https://yourGetURL.com", method: .get, parameters: ["":""], encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if let data = response.result.value{
print(response.result.value)
}
break
case .failure(_):
print(response.result.error)
break
}
}
Even works with
JSONEncoding.default
For Headers
If you are passing headers, make sure their type should be [String:String]
Go through the Parameter Encoding Link
https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md#parameter-encoding-protocol
Post method Alamofire 4.0 with Swift 3.0 and xCode 8.0
Alamofire.request(URL, method: .post, parameters: PARAMS)
.responseJSON { closureResponse in
if String(describing: closureResponse.result) == "SUCCESS"
{
// Sucess code
}
else
{
// Failure Code
}
}
My solution is if you are using headers, its type must be [String:String].
This error is up to parameters value. It has to be [String: String]
let url = URL(string: "http://yourURLhere")!
let params: [String: String] = ["name": "oskarko", "email": "youremail#here.com", "sex": "male"]
Alamofire.request(url, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).validate(statusCode: 200..<600).responseJSON() { response in
switch response.result {
case .success:
var result = [String:String]()
if let value = response.result.value {
let json = JSON(value)
}
case .failure(let error):
print("RESPONSE ERROR: \(error)")
}
}
I just resolved the same problem as you have. The problem is I have imported Alamofire in the header, so I just remove the Alamofire when call request. Like that:
request(.POST, patientIdUrl, parameters: nil, headers: nil, encoding:
.JSON)
I hope it can help you.
I ran into this same Extra argument 'method' in call error when my URL variable was out of scope.
In your case, please make sure both baseUrl and nextPatientIdUrl are in scope when they are being used Alamofire.request(patientIdUrl,..) method.
Hopefully this resolves your issue. Thanks You!
func API()
{
if Reachability.isConnectedToNetwork()
{
let headers = ["Vauthtoken":"Bearer \(apiToken)"]
print(headers)
// let parameter = ["iLimit":"10","iOffset":"0","iThreadId":"1"]
ApiUtillity.sharedInstance.showSVProgressHUD(text: "Loding...")
Alamofire.request(ApiUtillity.sharedInstance.API(Join: "vehicle/CurrentVehicleLists"), method:.get, parameters:nil, headers: headers).responseJSON { response in
switch response.result {
case .success:
print(response)
ApiUtillity.sharedInstance.dismissSVProgressHUD()
let dictVal = response.result.value
let dictMain:NSDictionary = dictVal as! NSDictionary
let statusCode = dictMain.value(forKey: "status") as! Int
if(statusCode == 200)
{
}
else if statusCode == 401
{
}
else
{
}
case .failure(let error):
print(error)
ApiUtillity.sharedInstance.dismissSVProgressHUD()
}
}
} else
{
ApiUtillity.sharedInstance.dismissSVProgressHUD()
ApiUtillity.sharedInstance.showErrorMessage(Title: "Internet Connection", SubTitle: "Internet connection Faild", ForNavigation: self.navigationController!)
}
}
For me this is working.
For GET Request
Alamofire.request("http://jsonplaceholder.typicode.com/todos/1/get").responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if response.result.value != nil{
print(response.result.value!)
}
break
case .failure(_):
print(response.result.error)
break
}
}
For POST
let parameters = NSDictionary(object: "nara", forKey: "simha" as NSCopying)
Alamofire.request("http://jsonplaceholder.typicode.com/posts", method: HTTPMethod.post, parameters: parameters as? Parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if response.result.value != nil{
print(response.result.value!)
}
break
case .failure(_):
print(response.result.error)
break
}
}
Thanks #Rajan Maheswari.
I fixed this issue with:
Reorder parameters (url then method type).
Change Encoding Enum to be "JSONEncoding.default" for example.
Note that: Alamofire methods signature change in Swift 3
Two things that I found worth noting.
Remove the first url label before its value. Use
Alamofire.request("https://yourServiceURL.com", method: .post,
instead of Alamofire.request(url: "https://yourServiceURL.com",
method: .post,.
Make sure the data type of the parameters is [String:
String]. Declare it explicitly.
I copy this code from Alamofire,create a URLRequest and used Alamofire.request(URLRequest) method, avoid this error
originalRequest = try URLRequest(url: url, method: method, headers: headers)
let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters)
I fixed this issue this way:
Just remove extra parameters, just parameters, encoding and headers, if these parameters are nil you can remove then and leave this way,
Alamofire.request(yourURLString, method: .post)
If you have added Alamofire files locally then don't use "Alamofire" before request
let apipath = “your api URL”
request(apipath, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { response in switch(response.result) {
case .success(_):
do {
let JSON = try JSONSerialization.jsonObject(with: response.data! as Data, options:JSONSerialization.ReadingOptions(rawValue: 0))
guard let JSONDictionary: NSDictionary = JSON as? NSDictionary else {
print("Not a Dictionary")
return
}
print("Post Response : \(JSONDictionary)")
}
catch let JSONError as NSError {
print("\(JSONError)")
}
break
case .failure(_):
print("failure Http: \(String(describing: response.result.error?.localizedDescription))")
break
}
}
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)
}
}
I'm currently trying to call a prepareForSegue method in an AlamoFire completion handler but it's not being called. Here is my code:
func loginMember (username: String, password: String, completionHandler: (String?, ErrorType?) -> ()) {
let headers = [
"Cache-Control": "no-cache",
"Content-Type": "application/json"
]
let parameters: [String: AnyObject] = [
"grant_type" : "password",
"username" : username,
"password" : password,
]
Alamofire.request(.POST, "\(baseURL)/oauth2/token", parameters: parameters, encoding: .JSON, headers: headers)
.validate()
.responseJSON { response in
switch response.result {
case .Success:
guard let value = response.result.value else {
completionHandler(nil, response.result.error)
return
}
let swiftyJsonVar = JSON(value)
accessToken = swiftyJsonVar["access_token"].stringValue
print("This is the login response:\(swiftyJsonVar)")
case .Failure(let error):
print("Sorry there was an error: \(error)")
return
}
}
}
This is what it looks like when called:
loginMember(username, password: password, completionHandler: { error in
dispatch_async(dispatch_get_main_queue()) {
self.performSegueWithIdentifier("loginToHomeSegue", sender: self)
}
}
)
Any ideas as to why the performSegueWithIdentifier isn't being called?
You're only calling your completion handler in the case where you enter your guard statement. You need to add calls for the case where you get your access token and your error case.
Alamofire.request(.POST, "\(baseURL)/oauth2/token", parameters: parameters, encoding: .JSON, headers: headers)
.validate()
.responseJSON { response in
switch response.result {
case .Success:
guard let value = response.result.value else {
completionHandler(nil, response.result.error)
return
}
let swiftyJsonVar = JSON(value)
accessToken = swiftyJsonVar["access_token"].stringValue
print("This is the login response:\(swiftyJsonVar)")
// Got the token, call handler
completonHandler(accessToken, nil)
case .Failure(let error):
print("Sorry there was an error: \(error)")
// Got an error, call handler
completionHandler(nil, error)
return
}
}