Alamofire Request Not Working in Swift 4 Project

Alamofire request not working in Swift 4 project

Use DispatchGroup to wait for the network request's completion:

import Alamofire
import Foundation

print("Hello, world!")

let group = DispatchGroup()

group.enter()
Alamofire.request("https://httpbin.org/get").responseJSON { response in
// handle the response
group.leave()
}

group.notify(queue: DispatchQueue.main) {
print("Goodbye, world!")
exit(0)
}
dispatchMain()

Alamofire request is not executed in swift 5

I think the below code helps you.

func Api_withParameters(aView : UIView, aWebServiceName : String, aDictParam : Dictionary<String, Any>, completeBlock: @escaping ( _ response: AnyObject) -> Void, errorBlock: @escaping ( _ error: AnyObject) -> Void) {

let passingURL = "\(BASEURL)/\(aWebServiceName)"
let jsonData = try? JSONSerialization.data(withJSONObject: aDictParam, options: [])
var jsonString = String(data: jsonData!, encoding: .utf8)
jsonString = jsonString!.filter { !"\\)(\n\t\r".contains($0) }

let passingParameter = [K_APIKEY:APIKEY, K_Data:jsonString!]

print("***** Web-Service URL : \(passingURL) \n Passing Parameter : \(passingParameter)")

Alamofire.request(passingURL, method: HTTPMethod.post, parameters: passingParameter, encoding: URLEncoding.default, headers: HEADER_CONTENT_TYPE).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
completeBlock(response.result.value as AnyObject)
break

case .failure(let error):
var errorDict = [String : Any]()
let errorcode : Int = error._code
if let httpStatusCode = response.response?.statusCode {
switch(httpStatusCode) {
case 404:
errorDict = ["errormsg" : "Invalid URL: \(passingURL)", "errorCode" : httpStatusCode]
default: break

}
} else {
if (String(errorcode) == "-1009"){
errorDict = ["errormsg" : "Please check your internet connection"]
}
else if(error.localizedDescription != ""){
errorDict = ["errormsg" : error.localizedDescription]
}
else{
errorDict = ["errormsg" : "Server unreachable please try again later."]
}
}
errorBlock(errorDict as AnyObject)
break
}
}
}

Swift 4.2 - Alamofire all of a sudden not working

Did you know you can parse JSON super easily with Swift 4.2?
I used it recently with a dialling code table view - the data was a local JSON file:

    struct Countries: Codable {
let countries: [Country]
}

struct Country: Codable {
let code: Int
let name: String
let flagImage: String
}

enum CodingKeys: String, CodingKey {
case code
case name
case flagImage
}

class CountryListVC: UITableViewController {

func loadJSON() {

if let path = Bundle.main.path(forResource: "countryDiallingCodes", ofType: "json") {

do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
let jsonObj = try JSONDecoder().decode(Countries.self, from: data)
print("JSON Object: ", jsonObj)
countries = jsonObj.countries

} catch let error {
print (error)
}
} else {
print ("Error in path")
}
}

can't call Alamofire.request(...)

That is an issue regarding this library, but if you add the required code it will work. Add this code for Alamofire and run :

Alamofire.request("http://api.androidhive.info/contacts/").responseData { (response) -> Void in

let responseJson = String(data : response.result.value!, encoding : String.Encoding.utf8)
print(responseJson)
}

Alamofire Request error only on GET requests

You're encoding the parameters as JSON in the body of the request, try encoding the parameters in the URL by changing the encoding to URL:

return Alamofire.request(.GET, urlString, parameters: parameters, encoding: .URL, headers: headers)

As this is the default behavior, you can simply remove it:

return Alamofire.request(.GET, urlString, parameters: parameters, headers: headers)

Failed response from **Alamofire** in swift 5

As it is throwing error related to Local, I think some language is defined and it doesn't accept * for Accept-Language header, try sending "en" in the header Accept-Language.

Check subtags for language:
http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry :

Test Code:

func callAPI() {

let params: Parameters = ["phoneNumber":"911234567890", "countryCode" : "91"]
let headers = [
"deviceId" : "jdhcbkerfjkr",
"osVersion": "3.2.3",
"deviceType": "ANDROID",
"resolution": "122x122",
"buildNumber": "3.2.1",
"Accept-Language": "en"]

AF.request("[Test-URL]",
method: .post,
parameters: params,
encoding: JSONEncoding.default,
headers: HTTPHeaders.init(headers)).response { response in
print(String(data: response.data!, encoding: .utf8)!)
}
}


Related Topics



Leave a reply



Submit