Alamofire: FAILURE responseSerializationFailed - ios

I'm trying to get the JSON from a URL to download using Alamofire.
Alamofire.request(requrl, method: .get, encoding: JSONEncoding.default)
.responseJSON { response in
print(response.result)
print(response.value)
debugPrint(response)
}
However the value of response.value is nil, and the request result status is FAILURE. The following is in the logs:
>[Data]: 919 bytes
[Result]: FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
[Timeline]: Timeline: { "Request Start Time": 561988246.258, "Initial Response Time": 561988246.446, "Request Completed Time": 561988246.447, "Serialization Completed Time": 561988246.447, "Latency": 0.189 secs, "Request Duration": 0.189 secs, "Serialization Duration": 0.000 secs, "Total Duration": 0.190 secs
The JSON url in a browser returns:
php script
<?php
header('Content-type: application/json');
//header('Content-Type: html; charset=utf-8');
$sqlstatement = $_GET["sqlstatement"];
// Create connection
$dbConnection=mysqli_connect("***.***.gear.host","****","*****!","****");
//$sqlstatement = "SELECT * FROM reeds.tbl_user";
// Check connection
if (mysqli_connect_errno())
{
// Print error message
echo mysqli_connect_error();
}
// Stores SQL statement, selecting all objects from testcomputing.name
// Check to ensure results > = 1
if ($result = mysqli_query($dbConnection, $sqlstatement))
{
// If so, then create a results array and a temporary one to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Encode the array to JSON and output the results
echo json_encode($resultArray);
}
// Close connections
mysqli_close($dbConnection);
?>

The issue was associated with the hosting provider. The provider I was originally using had strange security protocols installed, as such no JSON was being returned, after switching it work perfectly.

Related

Get Response using Alamofire

I am using Alamofire to make Get Response but unable to get the Valid Response . I am using below details . I dono where i am making mistake.
let myID = MEGHA-WORK SE-107
let headers = ["Authorization": "Basic \(base64Credentials)" , "ID": (myID).trimmingCharacters(in: .whitespaces) ]
let parameters:Parameters = ["ID": (myID).trimmingCharacters(in: .whitespaces)]
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 60
manager.request(url, method: .get, parameters: parameters, encoding: URLEncoding.queryString , headers: headers).responseJSON { (response) in
debugPrint(response)
if response.response?.statusCode == 200 || response.response?.statusCode == 201 {
if let value = response.result.value {
let json = JSON(value)
print(json)
completion(json, nil)
}
}
Task <343CF648-7C9A-4E03-9A82-A88BC41EA926>.<6> finished with error - code: -1005
Response
[Request]: GET https://my-services.myservices.com:443/prweb/api/v1/cases?ID=MEGHA-WORK%20SE-107
[Response]: nil
[Data]: 0 bytes
[Result]: FAILURE: Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={NSUnderlyingError=0x109ce9500 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x10d53db00 [0x1b271c310]>{length = 16, capacity = 16, bytes = 0x100201bba06d196d0000000000000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=https://my-services.myservices.com:443/prweb/api/v1/cases?ID=MEGHA-WORK%20SE-107, NSErrorFailingURLKey=https://my-services.myservices.com:443/prweb/api/v1/cases?ID=MEGHA-WORK%20SE-107, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-4, NSLocalizedDescription=The network connection was lost.}
[Timeline]: Timeline: { "Request Start Time": 553592494.567, "Initial Response Time": 553592497.615, "Request Completed Time": 553592497.615, "Serialization Completed Time": 553592497.616, "Latency": 3.049 secs, "Request Duration": 3.049 secs, "Serialization Duration": 0.000 secs, "Total Duration": 3.049 secs }
It seems that the reason is already printed there:
Code=-1005 "The network connection was lost."
Restarting the simulator and erasing all content and settings seems to fix this for others (Simulator->Hardware->Erase All Content and Settings...)
Please check this thread.
You can handle this way :
if (responseJson.response?.statusCode)! > 200 && (responseJson.response?.statusCode)! < 300{
// handle as appropriate because the response will be success
} else {
}
It may helps you to handle the crash. Thank you

Alamofire returns "The request timed out" with multipart image upload, but no problems with Postman

I am trying to POST data with an image using multipart upload with Alamofire. But it always returns "The request timed out" error.
When tried the same web service with Postman, it works as it should.
Basically Alamofire keeps trying for sometime,and returns this error, but with Postman I can see that the response is almost immediate and no timeout is recieved.
Here is a the helper method I created for the post request:
class func postRequestWithImage(image: UIImage, params : [String : String],success:#escaping (JSON) -> Void, failure:#escaping (NSError) -> Void){
SVProgressHUD.show()
Alamofire.upload(multipartFormData: { (multipartFormData) in
let imageData : Data = UIImageJPEGRepresentation(image, 0.6)!
for (key, value) in params{
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
multipartFormData.append(imageData, withName: "image")
}, to: WEBSERVICE_URL) { (encodingResult) in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
if response.result.isSuccess{
success(JSON(response.result.value!))
SVProgressHUD.dismiss()
}
else{
failure(response.result.error! as NSError)
}
}
case .failure(let encodingError):
failure(encodingError as NSError)
print(encodingError)
}
}
}
The debug response for the same is:
[Request]: http://website.com/v1/service/
[Response]: nil
[Data]: 0 bytes
[Result]: FAILURE: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x6080006441a0 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=http://website.com/v1/service/, NSErrorFailingURLKey=http://website.com/v1/service/, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.}
[Timeline]: Timeline: { "Request Start Time": 510773039.719, "Initial Response Time": 510773051.183, "Request Completed Time": 510773120.615, "Serialization Completed Time": 510773120.615, "Latency": 11.464 secs, "Request Duration": 80.895 secs, "Serialization Duration": 0.000 secs, "Total Duration": 80.896 secs }
I solved this. In my case there was a careless mistake. I used an extra slash in the url. I changed the web api to a different folder and while changing it in the iOS code I made this mistake.
I also had some changes made to the .htaccess file, so the request was not giving 404 error but instead trying to connect to that false address. errors that a beginner web developer will make

The data couldn’t be read because it isn’t in the correct format returned when getting google contacts

I am trying to retrieve goole contacts in my swift app and I am getting the error below. The user is successfully singing in.
func getUserContacts(email : String){
let urlString = "http://www.google.com/m8/feeds/contacts/\(email)/full"
Alamofire.request(urlString, method: .get)
.responseJSON { response in
switch response.result {
case .success(let JSON):
print(JSON as! NSDictionary)
case .failure(let error):
print(error.localizedDescription)
}
}
}
(lldb) po "http://www.google.com/m8/feeds/contacts/(email)/full"
"http://www.google.com/m8/feeds/contacts/emailhere#gmail.com/full"
(lldb) po error.localizedDescription
"JSON could not be serialized because of error:\nThe data couldn’t be read because it isn’t in the correct format."
(lldb) po response
▿ [Request]: GET http://www.google.com/m8/feeds/contacts/emailhere.com/full
[Response]: <NSHTTPURLResponse: 0x170033da0> { URL: http://www.google.com/m8/feeds/contacts/emailhere.com/full } { status code: 401, headers {
"Cache-Control" = "private, max-age=0";
"Content-Encoding" = gzip;
"Content-Length" = 8761;
"Content-Type" = "text/html; charset=utf-8";
Date = "Thu, 23 Feb 2017 14:19:11 GMT";
Expires = "Thu, 23 Feb 2017 14:19:11 GMT";
Server = GSE;
"X-Content-Type-Options" = nosniff;
"X-Frame-Options" = SAMEORIGIN;
"X-XSS-Protection" = "1; mode=block";
} }
[Data]: 11875 bytes
[Result]: FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
[Timeline]: Timeline: { "Request Start Time": 509552351.480, "Initial Response Time": 509552351.663, "Request Completed Time": 509552351.665, "Serialization Completed Time": 509552351.667, "Latency": 0.183 secs, "Request Duration": 0.185 secs, "Serialization Duration": 0.002 secs, "Total Duration": 0.187 secs }
▿ request : Optional<URLRequest>
▿ some : http://www.google.com/m8/feeds/contacts/emailhere.com/full
▿ url : Optional<URL>
▿ some : http://www.google.com/m8/feeds/contacts/emailhere.com/full
- cachePolicy : 0
- timeoutInterval : 60.0
- mainDocumentURL : nil
- networkServiceType : __ObjC.NSURLRequest.NetworkServiceType
- allowsCellularAccess : true
▿ httpMethod : Optional<String>
- some : "GET"
▿ allHTTPHeaderFields : Optional<Dictionary<String, String>>
- some : 0 elements
- httpBody : nil
- httpBodyStream : nil
- httpShouldHandleCookies : true
- httpShouldUsePipelining : false
▿ response : Optional<NSHTTPURLResponse>
▿ data : Optional<Data>
▿ some : 11875 bytes
- count : 11875
▿ pointer : 0x0000000104e24000
- pointerValue : 4376903680
▿ result : FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
▿ failure : AFError
▿ responseSerializationFailed : ResponseSerializationFailureReason
▿ timeline : Timeline: { "Request Start Time": 509552351.480, "Initial Response Time": 509552351.663, "Request Completed Time": 509552351.665, "Serialization Completed Time": 509552351.667, "Latency": 0.183 secs, "Request Duration": 0.185 secs, "Serialization Duration": 0.002 secs, "Total Duration": 0.187 secs }
- requestStartTime : 509552351.480039
- initialResponseTime : 509552351.66287899
- requestCompletedTime : 509552351.66534299
- serializationCompletedTime : 509552351.66746801
- latency : 0.18283998966217041
- requestDuration : 0.18530398607254028
- serializationDuration : 0.0021250247955322266
- totalDuration : 0.18742901086807251
▿ _metrics : Optional<AnyObject>
my problem was a permissions problem. I added GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/contacts.readonly") and gave my app access in https://myaccount.google.com/security
then this worked:
let urlString = "https://www.google.com/m8/feeds/contacts/default/full?access_token=\(GIDSignIn.sharedInstance().currentUser.authentication.accessToken!)&max-results=\(999)&alt=json&v=3.0"
Alamofire.request(urlString, method: .get)
.validate(contentType: ["application/json"])
.responseJSON { response in
switch response.result {
case .success(let JSON):
var json = JSON as! NSDictionary
print(JSON as! NSDictionary)
case .failure(let error):
print(error.localizedDescription)
}
}

Problems with JSON and Alamofire request

I am trying to send a request with the next code:
func getLogin(user: String, password: String) {
let url = URL(string: "https://www.url.es/api/login")!
let parameters: Parameters = [
"usuario" : "\(user)",
"clave" : "\(password)"]
let headers: HTTPHeaders = [
"Authorization": "Basic TOKEN"
]
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).validate()
.responseJSON { response in
print("repuesta")
print(response.request as Any) // original URL request
print(response.response as Any) // URL response
print(response.result.value as Any) // result of response serialization
debugPrint(response)
}
}
But I am getting this response:
[Request]: https://www.url.es/api/login
[Response]: <NSHTTPURLResponse: 0x608000220b40> { URL: https://www.url.es/api/login } { status code: 401, headers {
"Cache-Control" = "no-cache";
"Content-Length" = 28;
"Content-Type" = "text/plain; charset=utf-8";
Date = "Mon, 16 Jan 2017 20:44:14 GMT";
Expires = "-1";
Pragma = "no-cache";
Server = "Microsoft-IIS/8.5";
"Www-Authenticate" = Bearer;
"X-AspNet-Version" = "4.0.30319";
"X-Powered-By" = "ASP.NET";
} }
[Data]: 28 bytes
[Result]: FAILURE: responseValidationFailed(Alamofire.AFError.ResponseValidationFailureReason.unacceptableStatusCode(401))
[Timeline]: Timeline: { "Request Start Time": 506292395.911, "Initial Response Time": 506292396.351, "Request Completed Time": 506292396.352, "Serialization Completed Time": 506292396.353, "Latency": 0.440 secs, "Request Duration": 0.441 secs, "Serialization Duration": 0.000 secs, "Total Duration": 0.441 secs }
I am sending the request with paw http client and the response is ok.
I am working with swift3, alamofire 4 and iOS10
According to the response you have there it looks like your username and password is incorrect. Try printing the parameters dictionary to make sure it is correct. Something that can happen sometimes is if you forget to unwrap an optional value it will still get sent. For example
let optionalString:String? = "blablabla"
print(optionalString) //prints: Optional(blablabla)
Edit:
Another thing I noticed is you set the encoding to JSON but the header Content Type is PlainText. Try setting the encoding to URLEncoding.default and make sure the headers are set appropriately for what the server is expecting.

Code=-1001 "The request timed out."

I am working on a Swift project which requires a lot of consumption of APIs. Everything is working fine but sometimes (1 in 20), I get Code=-1001 "The request timed out." error while calling the API.
I am using Alamofire. I am attaching the code to call API.
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = myUrlContents.dataUsingEncoding(NSUTF8StringEncoding)
request.timeoutInterval = 15
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("\(myUrlContents.dataUsingEncoding(NSUTF8StringEncoding)!.length)", forHTTPHeaderField: "Content-Length")
request.setValue("en-US", forHTTPHeaderField: "Content-Language")
Alamofire.request(request)
.validate()
.responseJSON { [weak self] response in
if response.result.isSuccess {
if let result = response.result.value {
print("Result: \(result)")
completion(result: result as! NSDictionary)
}
}
else {
print(response.debugDescription)
}
}
And the log is
[Request]: <NSMutableURLRequest: 0x18855620> { URL: http://....... (url)}
[Response]: nil
[Data]: 0 bytes
[Result]: FAILURE: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSErrorFailingURLStringKey=http://.....(url) NSErrorFailingURLKey=http://.....(url), NSLocalizedDescription=The request timed out., _kCFStreamErrorDomainKey=4, NSUnderlyingError=0x18a08900 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102}}}
[Timeline]: Timeline: { "Request Start Time": 493582123.103, "Initial Response Time": 493582138.254, "Request Completed Time": 493582138.254, "Serialization Completed Time": 493582138.256, "Latency": 15.151 secs, "Request Duration": 15.151 secs, "Serialization Duration": 0.002 secs, "Total Duration": 15.153 secs }
I know I can increase the timeout period to avoid the error. But I want to know the actual reason why it is throwing the error. None of my API takes more than 2 seconds to return data. Then why it is showing latency of 15.151 seconds.
I am using LAMP stack on backend. Any help would be appreciated.
I had got the error with Code=-1001 “The request timed out.”.
I tried a few things. Nothing worked. Finally I found out that the problem was in my parameters that I'm sending in the request body to the server which were of wrong format(value was fine but type was wrong). Thats why the request was timing out coz the server wasn't able to process it. You can check that up if nothing else works for u.
I just encountered the same problem. I am using a GET request, and it turns out that using [:] is wrong. You have to use nil in GET request and [:] in POST request

Resources