Alamofire 4 request to open weather - swift

Working on my first Alamofire request and a code that is updated to Alamofire 4 . Can't get this Alamofire.request .responseJSON properly updated. I am looking at the Migration documentation: but not clever enough. Any suggestions how it should look?
let APIKey = "myAPIkey"
func retrieveCurrentWeatherAtLat(lat: CLLocationDegrees, lon: CLLocationDegrees,
block: (_ weatherCondition: WeatherCondition) -> Void) {
let url = "http://api.openweathermap.org/data/2.5/weather?APPID=\(APIKey)"
let params = ["lat": lat, "lon": lon]
// Send the request
Alamofire.request(url, method: .get, parameters: params)
.responseJSON { request, response, result in
switch result {
case .Success(let json):
let json = JSON(json)
block(weatherCondition: self.createWeatherConditionFronJson(json))
case .Failure(_, let error):
print("Error: \(error)")
}
}
}

maybe can help you
Alamofire.request(url, method: .get, parameters: params, encoding: JSONEncoding.default).responseJSON { (response) in
switch response.result {
case .Success(let json):
let json = JSON(json)
block(weatherCondition: self.createWeatherConditionFronJson(json))
case .Failure(_, let error):
print("Error: \(error)")
}
}

let APIKey = "YourApiKeyComesHere"
// Sending the request to Open Weather
func retrieveCurrentWeatherAtLat(lat: CLLocationDegrees, lon: CLLocationDegrees,
block: #escaping (_ weatherCondition: WeatherCondition) -> Void) {
let url = "https://api.openweathermap.org/data/2.5/weather?APPID=\(APIKey)"
let params = ["lat": lat, "lon": lon]
print("Sending request... \(url)")
let request = Alamofire.request(url, method: .get, parameters: params, encoding: URLEncoding(destination: .queryString)).responseJSON { (response) in
print("Got response from server: \(response)")
switch response.result {
case .success(let json):
let json = JSON(json)
block(self.createWeatherConditionFronJson(json: json))
print("Success: \(json)") //test
case .failure(let error):
print("Error: \(error)")
}
}
request.resume()
}

Related

Unable to get error message from completion handler of type Result

I am calling an api using Alamofire and trying to handle the error scenario. But I am not able to get the response for error in my completion handler implementation call.
Following is my Interactor code:
typealias CompletionHandlerType = (Result) -> Void
enum Result {
case Success(Any?)
case Failure(AppError)
}
func getLeads(stateId: String, completion: #escaping ([LeadInfo]?) -> Void) {
let urlString = baseURL + leadsURL
let params = ["user_id": UserDetails.getUserID() as AnyObject, "state_id": stateId as AnyObject]
NetworkOperations.fetchPostResponse(url: urlString, param: params, completionHandler: { (result) in
switch(result){
case .Success(let res):
guard let response = res as? [String: AnyObject] else {
completion(nil)
return
}
if let status = response["status"] as? Bool,
status,
let content = response["content"] as? [String: AnyObject] {
if let leads = content["leads"] as? [[String: AnyObject]] {
let array = leads.compactMap({ LeadInfo(json: $0) })
completion(array)
}
}
break;
case .Failure(let error):
print(error)
completion(nil)
break
}
})
}
API Handler code:
class NetworkOperations {
typealias CompletionHandlerType = (Result) -> Void
class func fetchPostResponse(url:String, param:[String:AnyObject], completionHandler: #escaping CompletionHandlerType){
Alamofire.request(url, method: .post, parameters: param, encoding: JSONEncoding.default, headers: getHeader()).responseJSON {
response in
switch response.result {
case .success:
completionHandler(Result.Success(response.result.value))
break
case .failure(let error):
completionHandler(Result.Failure(.serverConnectionFailure))
break
}
}
}
}
I get an error in fetchResponse method of NetworkOperations class. But I am not getting it in my Interactor method.
Try this
func getLeads(stateId: String, completion: #escaping ([LeadInfo]?) -> Void) {
let urlString = baseURL + leadsURL
let params = ["user_id": UserDetails.getUserID() as AnyObject, "state_id": stateId as AnyObject]
NetworkOperations.fetchPostResponse(url: urlString, param: params, completionHandler: { result in
switch(result) {
case .success(let res):
guard let response = res as? [String: AnyObject] else {
completion(nil)
return
}
if let status = response["status"] as? Bool, status,
let content = response["content"] as? [String: AnyObject] {
if let leads = content["leads"] as? [[String: AnyObject]] {
let array = leads.compactMap({ LeadInfo(json: $0) })
completion(array)
}
}
break;
case .failure(let error):
print(error.localizedDescription)
completion(nil)
break
}
})
}
API Handler code:
class NetworkOperations {
class func fetchPostResponse(url:String, param:[String:AnyObject], completionHandler: #escaping (Result<[LeadInfo]?,AppError>) -> Void){
Alamofire.request(url, method: .post, parameters: param, encoding: JSONEncoding.default, headers: getHeader()).responseJSON { response in
switch response.result {
case .success:
completionHandler(.success(response.result.value))
break
case .failure(let error):
completionHandler(failure(.serverConnectionFailure))
break
}
}
}
}
Notice how I replaced your Result enum with swift Result, now all you need to do is confirm to AppError to Error protocol
If it still doesn't work, let me know what is inside response.result in Alamofire.request

API working in Postman but giving error in Code

I am trying to call API in postman and its working fine, But If I am trying to call API in swift Alamofire, Its give me error-
My Code is-
func sendToServer(){
let urlString = "https://xxxxxxxxxx/TempService/SaveBarCodes"
let data: Parameters = ["SerialNo": "T8180399","Status":101]
Alamofire.request(urlString, method: .post, parameters: data,encoding: JSONEncoding.default, headers: nil).responseJSON {
response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}
}
Error is-
The JSON value could not be converted to System.Collections.Generic.List`1[BreakBulkModels.Model.WebapiModels.DtoInventoryApi]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.
Your API accepts as parameters an array of JSON objects but you are currently sending a JSON object:
{
"SerialNo": "T8180399",
"Status": 101
}
Because Parameters is a typealias to Dictionary<String, Any> (what you need is Array<Dictionary<String, Any>>) you have to do your parameter encoding yourself and then call request(_:) function of Alamofire passing your URLRequest:
do {
let urlString = "https://xxxxxxxxxx/TempService/SaveBarCodes"
let url = try urlString.asURL()
var request = URLRequest(url: url)
let data = [["SerialNo": "T8180399", "Status": 101]]
request = try JSONEncoding.default.encode(request, withJSONObject: data)
Alamofire.request(request).responseJSON { response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}
} catch {
print(error)
}
Edit: With Alamofire v5 there is a more elegant way by using Encodable protocol:
struct BarCode: Encodable {
var SerialNo: String
var Status: Int
}
func sendToServer(){
let urlString = "https://xxxxxxxxxx/TempService/SaveBarCodes"
let data = [BarCode(SerialNo: "T8180399", Status: 101)]
AF.request(
urlString,
method: .post,
parameters: data,
encoder: JSONParameterEncoder.default
).responseJSON { response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}
}

Why is Alamofire POST-Api-call not working?

The POST-parameters are not passed. Why?
Is there another possibility to make POST-API-Calls?
let parameters: [String: String] = ["username" : "test", "password" : "test"]
Alamofire.request("http://192.168.2.117/evk-ph/api/verify_user.api.php",
method: .post,
parameters: parameters,
encoding: JSONEncoding.default,
headers: nil).responseJSON { response in
switch response.result {
case .success:
print(response)
case .failure(let error):
print(error)
}
}
Here is a code that maybe work for use just do a simple changes in your code
func postJSON() {
let param = ["username":tFusername.text!,"password":tFpassword.text!] as NSDictionary //GET TEXTFIELD VALUE
let url = "YOUR URL HERE"
Alamofire.request(url, method: .post, parameters: (param as! Parameters), encoding: JSONEncoding.default).responseJSON { response in
switch response.result{
case .success(let json):
print(json)
DispatchQueue.main.async {
print(param)
//HANDLE YOUR CODE HERE
}
case .failure(let error):
print(error)
}
}
Use this Function in your viewDidLoad() or as you required.

Alamofire Swift convert

Hi I want to make a request to API, but when send, console show me
invalidURL
Alamofire.request("https://.../api/v1.8/set/order/?address=\(address)&email=\(email)&information=\(information)&name=\(name)&order=\(parameters)&password=\(password)&paymentType=\(paymentType)&phone=\(phone)&token=\(token)&userID=\(userID)&wihtRegistration=\(wihtRegistration)").validate(statusCode: 200..<300)
.responseJSON { response in
switch response.result
{
case .failure(let error):
print(error)
case .success(let value):
print(value)
print("Request: \(response.request)")
}
}
How can I convert in Alamofire?
I have created this custom method. Call this by passing required parameter:-
Without JSON Encoding
func requestWithoutJSONEncoding(_ method: HTTPMethod
, _ URLString: String
, parameters: [String : AnyObject]? = [:]
, headers: [String : String]? = [:]
, completion:#escaping (Any?) -> Void
, failure: #escaping (Error?) -> Void) {
Alamofire.request(URLString, method: method, parameters: parameters, headers: headers)
.responseJSON { response in
switch response.result {
case .success:
completion(response.result.value!)
case .failure(let error):
failure(error)
}
}
}
With JSON Encoding
func request(_ method: HTTPMethod
, _ URLString: String
, parameters: [String : AnyObject]? = [:]
, headers: [String : String]? = [:]
, completion:#escaping (Any?) -> Void
, failure: #escaping (Error?) -> Void) {
Alamofire.request(URLString, method: method, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
.responseJSON { response in
switch response.result {
case .success:
completion(response.result.value!)
case .failure(let error):
failure(error)
}
}
}
Try this
let jsonObject = [["code": 404, "counts": 15]]
let json = JSON(jsonObject)
// Generate the string representation of the JSON value
let jsonString = json.rawString(.utf8)!
let params = ["name": name, "phone": phone, "address": address, "information": information, "email": email, "userID":userID, "wihtRegistration": wihtRegistration, "password": password, "token": token, "paymentType": paymentType, "order" : jsonString] as [String : Any]
Alamofire.request("http:...", method: .get, parameters: params)
.responseString { response in
#if DEBUG
(request!.url!.absoluteString)\n\(request!.httpBody.map { body in String(data: body, encoding: .utf8) ?? "" } ?? "")")
switch response.result {
case .success(let value):
print("Response with content \(value)")
case .failure(let error):
print("Response with error: \(error as NSError): \(response.data ?? Data())")
}
#endif
}

Custom made Creditcard Expiry Date field

I'm trying to make a POST API request using Alamofire 4.0 and Swift 3.0 but I'm having a tough time with it.
My Postman looks like this:
And using Basic Auth
I can't even get my code to compile for now and I've no idea why. This is my function:
func testCall(token:String, completionHandler: #escaping ((AnyObject?, Error?) -> Void)) {
let urlString = Constant.apiUrlString + Constant.apiPostOrderCard
print(urlString)
let parameters = ["test" : "test"]
Alamofire.request(urlString, method: .post, parameters: parameters, encoding: .JSON, headers: self.header).validate().responseJSON { (request, response, result) -> Void in
switch result {
case .Success(let value):
print(value)
completionHandler(value, nil);
break
case .Failure(let data, let error):
self.handleFailure(data, error: error, response: response, completionHandler: completionHandler)
break
}
}
What am I doing wrong?
Did you just migrate to Alamofire 4? There are couple of syntax changes, you need to read the migration guide when there is an version update.
Here is the updated code :)
func testCall(token:String, completionHandler: #escaping ((AnyObject?, Error?) -> Void)) {
let urlString = Constant.apiUrlString + Constant.apiPostOrderCard
let parameters : Parameters = ["test": "test"]
Alamofire.request(urlString, method: .post, parameters: parameters).validate().responseJSON { response in
if let status = response.response?.statusCode {
switch(status){
case 200:
if let result = response.result.value {
let JSON = result as! NSDictionary
// implement your logic here
completionHandler(value, nil);
}
break
case 400:
// implement your logic here
self.handleFailure(data, error: error, response: response, completionHandler: completionHandler)
break
default:
break
}
}
}
}
the Parameters is Alamofire's object, feel free to use its and the constructor had changed also.
Just replace your encoding: .JSON to encoding: JSONEncoding.default and ensure parameters has type Parameters:
Alamofire.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: self.header).validate().responseJSON { response in
switch response.result {
case .success(let json): //do something
case .failure(let error): // do something
}
}