Custom made Creditcard Expiry Date field - swift

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

Related

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

the alamofire isn't doing a proper connection to the api

i am trying to get a response that contain json from openweathermap api,
but from the debugger it seems that when he get to the code block of alamofire its just skips it
here is the block of code that i am using for this task
func printJson(){
Alamofire.request("https://api.openweathermap.org/data/2.5/find?appid=6ad1f143546b8c6d761ecbda6a34a005&q=yavne", method: .get).responseJSON { response in
if response.data != nil {
var json : JSON
do{
json = try JSON(data: response.data!)
print(json)
}catch{}
}
}
}
Use this helper class to make API calls.
class NetworkHandler {
static let shared = NetworkHandler()
func sendRequest(withUrl url:String,andBody body:[String:Any]? = [:],
completionHandler: #escaping ((_ status: Bool,_ response:Any) -> Void)) {
DispatchQueue.global(qos: .userInitiated).async {
Alamofire.request(url, method: .post, parameters: body,encoding: JSONEncoding.default, headers: nil).responseJSON {
response in
guard response.response?.statusCode == 200 else{
completionHandler(false,"Service Temporarily Unavailable.\nPlease check your internet connection or contact your Service provider.")
return
}
switch response.result {
case .success:
completionHandler(true,response.value!)
break
case .failure(let error):
completionHandler(false,error.localizedDescription)
}
}
}
}
}

Could not cast value of type T.Type to T

I’m trying to make an universal method using AlamofireObjectMapper for sending request where input is BasicMappable(generic type) and output is a response
func sendRequest<T>(endPoint: String,
parameters: Parameters,
method: HTTPMethod,
mappingObject: T.Type) -> T where T : BaseMappable {
var answer = T.self
Alamofire.request(applicationBaseURL + endPoint,
method: method,
parameters: parameters,
headers: nil)
.responseObject { ( response: DataResponse<T>) in
let data = response.result.value
answer = data as! T.Type
}
return answer as! T
}
So I use this method in VC like that:
let authResponse = requestHelper.sendRequest(endPoint: "/auth/users/create/",
parameters: params,
method: .post,
mappingObject: AnswerClass.self)
And it builds well.
But when I’m trying to send request I’ve got a crash and error
Could not cast value of type 'Travel.AuthController.AnswerClass.Type' (0x110186bf8) to 'Travel.AuthController.AnswerClass' (0x10de153b0).
2019-04-15 18:42:28.811494+0300 Travel[9951:596186] Could not cast value of type 'Travel.AuthController.AnswerClass.Type' (0x110186bf8) to 'Travel.AuthController.AnswerClass' (0x10de153b0).
I've already done it in VC with this
Alamofire.request(applicationBaseURL + "/auth/users/create/",
method: .post,
parameters: params,
headers: nil)
.responseObject { (response: DataResponse<AnswerClass>) in
let loginRespone = response.result.value
for error in loginRespone?.errors ?? [] {
print(error.detail)
print(error.source)
print(error.status)
}
And it works well
But I want to make this method universal for the whole project
How to correctly cast value of these types or are there any other ways ?
Thank you, #Kamran for your help!
My final solution is:
class RequestHelper {
func sendRequest<T>(endPoint: String,
parameters: Parameters,
method: HTTPMethod,
mappingObject: T.Type,
completion: #escaping (_ response: T?, _ error: Error?) -> Void) where T : BaseMappable {
Alamofire.request(applicationBaseURL + endPoint,
method: method,
parameters: parameters,
headers: nil)
.responseObject { ( response: DataResponse<T>) in
switch response.result {
case .success(let value):
completion(value, nil)
case .failure(let error):
completion(nil, error)
}
}
}
}
You need to use completionHandler as below to get the object,
func sendRequest<T>(endPoint: String,
parameters: Parameters,
method: HTTPMethod,
mappingObject: T.Type,
completion: (T?, Error?) -> Void) {
Alamofire.request(applicationBaseURL + endPoint,
method: method,
parameters: parameters,
headers: nil)
.responseObject { ( response: DataResponse<T>) in
switch response.result {
case .success(let value):
completion(value, nil)
case .failure(let error):
completion(nil, error)
}
}
}

How do I trace the response of this call in Swift Xcode?

Data in the below call is nil so the call is failing:
postRequest("/api/users/signup", params: params, headers: nil) { data in
guard data != nil else {
return completionHandler(nil, UsersStoreError.CannotSignup)
This is the postRequest function:
private func postRequest(_ url: String, params: Parameters?, headers: HTTPHeaders?, completion: #escaping([String:Any]?) -> Void) {
let enc = JSONEncoding.default
let url = AppConstants.ENDPOINT + url
Alamofire
.request(url, method: .post, parameters:params, encoding:enc, headers:headers)
.validate()
.responseJSON { response in
switch (response.result) {
case .success(let data): completion((data as! [String:Any]))
case .failure(_): completion(nil)
}
}
}
How can I trace the response of this call?
Set a breakpoint in the responseJSON block in your postRequest method and inspect/print the response parameter. That should give you information about the request and the response.
It's possible that the response isn't valid JSON. To check what you're actually getting back, add this to responseJSON (before your switch):
debugPrint(String(data: response.data!, encoding: .utf8))

Alamofire 4 request to open weather

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