Loop JSON requests to backend (REST API) - ios

I am sending request to the backend (REST API). My task: If the JSON response does not come in the required format, or returns an error, then start the request cycle - 3 attempts, and if these three attempts fail, then exit, else go next (HomePage)
Here is code:
func checkUsers(){
let headers: HTTPHeaders = ["Content-Type" : "application/json"]
NetworkManager.sharedInstance.manager.request("https://restapi.com/user",
method: .get,
parameters: nil,
encoding: JSONEncoding.default,
headers: headers).responseJSON { (response) -> Void in
switch response.result {
case .success(let value):
let response = JSON(value)
print("JSON Response: \(response)")
if response["operation"].stringValue == "loginerror" {
print("Error")
self.showNotRegisteredScreen()
} else {
usersFIO = response["userName"].stringValue
self.didFinishLogin()
}
case .failure(let error):
print("fail to fecth data",error)
self.showErrorScreen()
}
}
Please tell me how to start a request cycle in which to specify three attempts
P.S.: Using Alamofire and SwiftyJson pods
Thanks in advance!

It works for me with Alamofire 5
lazy var manager: Alamofire.Session = {
let configuration = URLSessionConfiguration.default
let retryPolicy = RetryPolicy(retryLimit: 3)
let interceptor = Interceptor(retriers: [retryPolicy])
let manager = Alamofire.Session(configuration: configuration, interceptor: interceptor, serverTrustManager: serverTrustManager, eventMonitors: [CertificateAuthAdapter()])
return manager
}()

Related

swift 3.0: Extra argument in call [duplicate]

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

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

Alamofire Parameter missing in response

I install pod file of Alamofire for calling web service and successfully retrieve data when there is no parameter pass to web service but when I try to pass parameter It shows this parameter missing.
Here is my code:
let parameters: Parameters = ["client_id": "1","user_token":"A4YkkH5FdTbRCI8Mk98s"]
let url = "http://***********/index.php/Web_api/get_client_profile"
Alamofire.request(url , method: .post, parameters: 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
}
}
RESPONSE:
{
"message : client_id parameter missing",
"Code : 500"
}
What I am doing wrong ? Please help me with it.
Thank you
After banging my head for like 6 Hours I figured a different approach, here is a way of calling it, which works:
var request: Alamofire.Request? {
didSet {
oldValue?.cancel()
}
}
func loadDataFromServer(message:String?) {
// Prerequisites for Connection to Server
let timeParameter = self.getLastTimeStamp()
let url = "http://your.amazing.url/path/component/classs"
let parameter = ["timestamp":timeParameter]
//sho hud only of there is no data listed
if message != nil {
HUD.show(HUDContentType.label("Loading.."))
}
self.request = Alamofire.request(url, method: .post, parameters:parameter)
if let request = request as? DataRequest {
request.responseString { response in
PKHUD.sharedHUD.hide()
do{
let dictionary = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
//Save and Fetch
self.saveTimestamp(dictionary: dictionary, wsEntity: "Section")
self.saveDataInPersisanceStorage(articalDictionary: dictionary)
self.fetchDatafromCore()
//HUD.flash(.success, delay:1.0)
}catch{
//HUD.flash(.error, delay:1.0)
}
}
}
}

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 returns .Success on error HTTP status codes

I have a pretty simple scenario that I'm struggling with. I'm using Alamofire to register a user on a rest API. The first call to register is successful and the user can log in. The second call, when trying to register with the same email address should result in a HTTP status code 409 from the server. Alamofire, however, returns a .Success with an empty request and response. I have tested this this API with postman and it correctly returns a 409.
Why is Alamofire not returning .Failure(error), where the error has status code info etc?
Here is the call I run with the same input each time.
Alamofire.request(.POST, "http://localhost:8883/api/0.1/parent", parameters: registrationModel.getParentCandidateDictionary(), encoding: .JSON).response(completionHandler: { (req, res, d, e) -> Void in
print(req, res, d, e)
})
From the Alamofire manual:
Validation
By default, Alamofire treats any completed request to be successful,
regardless of the content of the response. Calling validate before a
response handler causes an error to be generated if the response had
an unacceptable status code or MIME type.
You can manually validate the status code using the validate method, again, from the manual:
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.response { response in
print(response)
}
Or you can semi-automatically validate the status code and content-type using the validate with no arguments:
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.validate()
.responseJSON { response in
switch response.result {
case .success:
print("Validation Successful")
case .failure(let error):
print(error)
}
}
If using response, you can check the NSHTTPURLResponse parameter:
Alamofire.request(urlString, method: .post, parameters: registrationModel.getParentCandidateDictionary(), encoding: JSONEncoding.default)
.response { response in
if response.response?.statusCode == 409 {
// handle as appropriate
}
}
By default, 4xx status codes aren't treated as errors, but you can use validate to treat it as an such and then fold it into your broader error handling:
Alamofire.request(urlString, method: .post, parameters: registrationModel.getParentCandidateDictionary(), encoding: JSONEncoding.default)
.validate()
.response() { response in
guard response.error == nil else {
// handle error (including validate error) here, e.g.
if response.response?.statusCode == 409 {
// handle 409 here
}
return
}
// handle success here
}
Or, if using responseJSON:
Alamofire.request(urlString, method: .post, parameters: registrationModel.getParentCandidateDictionary(), encoding: JSONEncoding.default)
.validate()
.responseJSON() { response in
switch response.result {
case .failure:
// handle errors (including `validate` errors) here
if let statusCode = response.response?.statusCode {
if statusCode == 409 {
// handle 409 specific error here, if you want
}
}
case .success(let value):
// handle success here
print(value)
}
}
The above is Alamofire 4.x. See previous rendition of this answer for earlier versions of Alamofire.
if you use validate() you'll loose the error message from server, if you want to keep it, see this answer https://stackoverflow.com/a/36333378/1261547
Here is my code for AlamoFire error catching:
switch response.result {
case .success(let value):
completion(.success(value))
case .failure(var error):
var errorString: String?
if let data = response.data {
if let json = try? (JSONSerialization.jsonObject(with: data, options: []) as! [String: String]) {
errorString = json["error"]
}
}
let error = MyError(str: errorString!)
let x = error as Error
print(x.localizedDescription)
completion(.failure(x))
}
and the MyError class difinition:
class MyError: NSObject, LocalizedError {
var desc = ""
init(str: String) {
desc = str
}
override var description: String {
get {
return "MyError: \(desc)"
}
}
//You need to implement `errorDescription`, not `localizedDescription`.
var errorDescription: String? {
get {
return self.description
}
}
}

Resources