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

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

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

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

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

Pass token with post request using Alamofire

I'm new to iOS and I would like some direction on why my code isn't working. I'm trying to make a call to a url and pass a token and get the response. My response is coming back with a 404 status code.
let reverse = ["token": "831b21c47a7f7daee7d6e4e3fa11deaa"]
let url = "http://challenge.com"
Alamofire.request(url, parameters: reverse).responseJSON { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
Try bellow code:
Alamofire.request(url, method: .get, parameters: reverse, encoding: JSONEncoding.default).responseString { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
Try this Code:
This code is also handle the error when response will be the blank and also the Internet connection is disable.
func apiCall(params : [String:AnyObject],block:([String:AnyObject]->Void)?) {
if Reachability.isConnectedToNetwork(){
Alamofire.request(.POST, URL, parameters: params, encoding: .JSON, headers: nil).responseJSON{
response in
let data = response.result.value
if data == nil{
if response.result.error?.code == -1005 {
print(response.result.error?.localizedDescription)
}
else{
switch response.result {
case .Success:
block!(data as! [String:AnyObject])
case .Failure(let error):
print(error)
}
}
}
}
else{
print(NO_NETWORK)
}
}