Swift 3 Alamofire is sometimes going to failure block - swift

Alamofire.request(NEWS_FEED_URL).responseJSON { response in
guard let newsResponse = response.result.value as? [[String:String]] else{
print("Error")
return
}
print("JSON: \(newsResponse)")
This is my alamofire code to get response from server. Most of the time it is working fine but sometime it goes failure and print Error. Even if I paste print("JSON:", newsResponse) in failure block it shows the response but it is not going to the success block. I also print the status code once. Its giving me 200. My Internet is working good, the related url is giving response in postman. But sometimes it is not working why?

Try this method
func apiRequest(method:String, urlMethod:String, parametersDictionary:NSMutableDictionary, success:#escaping successDictionaryBlock, failure: #escaping failBlockErrorMessage){
let requestUrl = "Request URL"
Alamofire.request(requestUrl, method: .post, parameters: (parametersDictionary as NSDictionary) as? Parameters , encoding: JSONEncoding.default, headers: nil).responseJSON { response in
print(response)
print(requestUrl)
if(response.result.error == nil){
if((response.response?.statusCode)! < 500){
if(response.response?.statusCode == 200){
if let JSON = response.result.value {
print(JSON)
let dict = JSON as! NSDictionary
let status :Bool = dict["status"] as! Bool
if(status){
success(dict)
}else{
failure(dict["message"] as! String)
}
}
}else{
failure("Something went wrong please try again")
}
}else{
failure("Something went wrong please try again")
}
}
}
}

Related

URLSession with URLCredential

I would like to get data from server, but credential (username, password. Not Basi Authentification) is necessary to get it. Therefore, I try to use URLSession with URLCredential as following:
https://developer.apple.com/documentation/foundation/url_loading_system/handling_an_authentication_challenge
However, I could not understand this document...
So could you tell me how to use URLSession with URLCredential?
I tried URLSession like:
func startLoad() {
let url = URL(string: "https://www.abcde-test-url.com/")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print("client error: \(error.localizedDescription) \n")
return
}
guard let data = data, let response = response as? HTTPURLResponse else {
print("no data or no response")
return
}
if response.statusCode == 200 {
print(data)
} else {
print("error status code: \(response.statusCode)\n")
}
}
task.resume()
}
But I couldn't understand the usage with URLCredential.

JSONSerialization swift response is always nil

I'm performing a post request over my rest api that I built in node. Then the data are stored in a mongodb collection.
This is my code that I use to post the request:
// create dataTask using the session object to send data to the server
let task = session.dataTask(with: request) { data, response, error in
if let error = error {
print("Post Request Error: \(error.localizedDescription)")
return
}
// ensure there is valid response code returned from this HTTP response
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode)
else {
print("Invalid Response received from the server")
return
}
// ensure there is data returned
guard let responseData = data else {
print("nil Data received from the server")
return
}
do {
// create json object from data or use JSONDecoder to convert to Model stuct
if let jsonResponse = try JSONSerialization.jsonObject(with: responseData, options: .mutableContainers) as? [String: ErrorHandler] {
print(jsonResponse)
DispatchQueue.main.async {
self?.isLoading = false
self?.signedIn = true
}
} else {
print("data maybe corrupted or in wrong format")
throw URLError(.badServerResponse)
}
} catch let error {
print(error.localizedDescription)
}
}
task.resume()
The problem is that the responseJson is always nil. I tried to perform the same request with postman and I get the response correctly. What is the problem? Also because the data are correctly uploaded everywhere.
This is my postman result of the same post request.

Alamofire request is send twice

I’m alamofire request, and I found the request is sent twice. Is it an alamofire bug?
I tried to put a breakpoint, but it's not called twice and there is no button call this function twice or trigging twice.
Here is my code
ARSLineProgress.show()
guard let url = URL(string: "https://laghmat.kbmediawebites.com/api/rest/account") else {return}
let headers = ["X-Oc-Merchant-Id": MerchantId, "X-Oc-Session": K_Defaults.string(forKey: "sessionID"),"ACCEPT":"application/json"]
let params = [
"firstname": firstName,
"lastname": lastName,
"email": email,
"telephone": phone
] as! [String : String]
Alamofire.request(url, method: .put, parameters: params,encoding: JSONEncoding.default, headers: headers as! HTTPHeaders).responseJSON {
response in
switch response.result {
case .success:
print(response)
guard let data = response.data else { return }
do {
let value = try JSONDecoder().decode(GeneralResponse.self, from: data)
if value.success == 1 {
ARSLineProgress.showSuccess()
var user = GlobalHelpers.getUser()
user?.firstname = firstName
user?.lastname = lastName
user?.telephone = phone
user?.email = email
GlobalHelpers.setUser(user)
self.dismiss(animated: true, completion: nil)
} else {
ARSLineProgress.showFail()
self.alert(msg: LanguageManger.localize(word: "serverError"))
}
} catch let error {
ARSLineProgress.showFail()
self.alert(msg: LanguageManger.localize(word: "serverError"))
print(error)
}
break
case .failure(let error):
ARSLineProgress.showFail()
self.alert(msg: LanguageManger.localize(word: "serverError"))
print(error)
}
}
well I recommend you that lock all the buttons in the view, when the request is made.
for viewW in view.subviews
{
if let buttonV = viewW as? UIButton
{
buttonV.isUserInteractionEnabled = false
}
}
obviously, you have to lock at the beginning and unlock at the end.
if this isn't works, put a breakpoint in this line
switch response.result {
the first time, you will see that you don't have a status code, because the server not yet responding, then press next step, and you will see a status code, because the server already responds to you.
that doesn't mean the request is made twice, I think that this happen because the handshake is happening.

Alamofire Post Request is not Executed

I'm making a POST Request to my API. All of a sudden the request is being skipped. I have tried to debug into it, but until now without success.
This is my request:
#IBAction func checkLogin(_ sender: Any) {
guard let managedContext = self.managedObjectContext else { return }
let user = NSEntityDescription.insertNewObject(forEntityName: User.identifier, into: managedContext) as! User
let url = ""
let parameters: Parameters =
["username" : usernameTextField.text!, "password" : passwordTextField.text!]
Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default).responseJSON { (responseData) -> Void in
let results = JSON(responseData.result.value!)
print(results)
user.firstName = results["firstname"].string!
let responseString : String = responseData.response?.allHeaderFields["Set-Cookie"] as! String
if let range = responseString.range(of: ";"){
let startIndex = (responseString.range(of: "="))
let cookie = responseString[(startIndex?.upperBound)!...range.lowerBound]
user.setValue(cookie, forKey: "token")
}
} do {
try self.dataController.saveContext()
}catch {
print("Save Error User")
}
I'm Using Alamofire 4.5 with Swift 3.1.
Please use different types of data request handling block and check again.
Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default)
.responseJSON { response in
print("JSON Response")
}
.responseData { response in
print("Data Response")
}
.responseString { response in
print("String Response")
}
.responsePropertyList { response in
print("PropertyList Response")
}

dataTaskWithURL sometimes no return

I have a very simple http request which will return a JSON data. Here is my code:
let query = NSString(format: "http://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=test",src, dest, phrase )
let url = NSURL(string: query)
let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in
if let httpRes = response as? NSHTTPURLResponse {
println("status code=",httpRes.statusCode)
if httpRes.statusCode == 200 {
println(NSString(data: data, encoding: NSUTF8StringEncoding))
// parse data
let phrase = Phrase.parse(data)
println(phrase.description)
}
}
}
task.resume()
Sometimes the completionHandler isn't called at all. I suspect it's the problem of the server. But when I input the same url into my browser and tried a dozens times. There was no problem at all. The data was returned everything when I refresh the browser.
Is there anything wrong in my code? Thanks
The code works OK for me. I suggest you can make this change to your code (an else clause):
if let httpRes = response as? NSHTTPURLResponse {
println("status code=",httpRes.statusCode)
if httpRes.statusCode == 200 {
println(NSString(data: data, encoding: NSUTF8StringEncoding))
// parse data
let phrase = Phrase.parse(data)
println(phrase.description)
}
} else {
println("error \(error)") // print the error!
}
So you will have a better idea if anything goes wrong