Not getting response from Alamofire - ios

Using Alamofire for JSON response from remote.
I have had a very weird issue. While running my app on a device connected through cable is working fine and getting all response. But when the device gets disconnected through cable response time getting increased to 5 minutes to 30 minutes and if I connect the device to charging or to MacBook again it's work fine but stuck if not connected.
func getData()
{
let baseUrl = URL.init(fileURLWithPath: "")
let headers:HTTPHeaders = ["Content-Type":"application/json"]
Alamofire.request(baseUrl, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers)
.responseJSON
{ response in
switch(response.result) {
case .success(_):
if response.result.value != nil{
let jsonData = response.result.value as? Dictionary<String,AnyObject>
print(jsonData)
}
case .failure(_):
print(response.result.error!)
break
}
}
}

Are you using any other class for Session manager? If yes then that may cause problem. So remove that one.

can you share your api request ?.
One possible solution to add Transport security as:
Add this code in info.plist, inside the root tag
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoadsInWebContent</key>
<true/>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>

Related

iOS - Alamofire - cannot reach server on WiFi

I am slowly distributing my app to Beta testers via TestFlight.
A few of them have already reported that the app showed “No Internet connection” while on WiFi. As soon as they switched to cellular everything started to work. The WiFi works for everything else.
I use Alamofire as a framework to make HTTPRequests and when these requests fail, “No Internet connection” error is displayed.
My backend service is hosted on Google Cloud
My domain is registered using AWS Route 53
I use SSL certificates managed by Google
All HTTPRequests are sent to https://api.myapp.com (where myapp.com is hosted on AWS).
All of the testers have Automatic DNS resolution set in Settings -> WiFi -> (i) -> DNS
Any ideas what the cause can be or how I can further investigate this issue?
This is the piece of code used to make GET requests:
func getJSON(_ url: String,
parameters: [String: String] = [:],
headers: [String: String] = [:],
completionHandler: #escaping (_ result: JSON?,
_ headers: [String: String]?,
_ statusCode: Int?,
_ error: Error?) -> Void) {
Self.sessionManager.request(
url,
method: .get,
parameters: parameters,
headers: self.createHeaders(headers: headers),
interceptor: self,
requestModifier: { $0.timeoutInterval = HttpClient.defaultTimeoutInterval }
).validate().responseJSON { response in
switch response.result {
case .success(let data):
let json = JSON(data)
completionHandler(json, self.getResponseHeaders(httpUrlResponse: response.response), response.response?.statusCode, nil)
case .failure(let error):
completionHandler(nil, self.getResponseHeaders(httpUrlResponse: response.response), response.response?.statusCode, error)
}
}
}
The connection error is displayed when error != nil. When it happens, it happens for all HTTP endpoints (does not matter if an endpoint requires authentication or authorization, all HTTP requests fail).

Unable to call some API's in Xcode

I'm dealing with a strange issue where I'm not able to hit some API's through iOS simulator in XCode.
Version: Xcode 10.3
I've tried using the following:
https://finnhub.io/api/v1/stock/profile2?symbol=GOOGL&token=
https://www.alphavantage.co/query?function=OVERVIEW&symbol=IBM&apikey=demo
I'm able to hit both endpoints through the browser, replacing both with a completely unrelated api: https://cat-fact.herokuapp.com/facts works, I'm able to see the response immediately as expected.
I've added the following to my Info.plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Code:
let apiBaseUrl = "https://www.alphavantage.co/query?function=OVERVIEW&symbol=IBM&apikey=demo"
func getStock(symbol: String) {
if let url = URL(string: apiBaseUrl) {
let task = URLSession.shared.dataTask(with: url, completionHandler: {
data, res, err in
if let error = err {
print(error)
} else {
var result: Any! = nil
do
{
result = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
}
catch{
print("exception: ")
}
print(result)
}
})
task.resume()
}
}
In my console I see the following:
HTTP load failed (error code: -999 [1:89])
PAC result block not invoked
Received XPC error Connection invalid for message type 3 kCFNetworkAgentXPCMessageTypePACQuery
I solved this issue as below :
I went into
System Preferences > Network > Advanced > Proxies
and unticked "Auto Proxy Discovery"
My calls now work.

The Network Connection was lost from Alamofire

I got this error many times in my project and it very irritates me because I have full internet connectivity though I get this error repeatedly.
What is the solution...?
I am using
Swift - 3.3
Alamofire - 4.7.3
API Calling Code:
class func post(_ URL: String, withParams params: [String : AnyObject], onView parentView: UIViewController, hnadler completion: #escaping ([AnyHashable: Any]!) -> Void) {
var URLString = String()
URLString = APIConstants.kServerURL + URL
var headers = [String: String]()
headers["Content-Type"] = "application/x-www-form-urlencoded"
Alamofire.request(URLString,method: .post, parameters: params , headers : headers)
.validate(contentType: ["application/vnd.api+json"])
.responseJSON { response in
switch response.result {
case .success( _):
var completionVarible = [NSObject : AnyObject]()
completionVarible = response.result.value as! [AnyHashable: Any]! as [NSObject : AnyObject]
completion(completionVarible)
case .failure(let error):
self.handleFailureResponse(Error: error as NSError?, parentView: parentView)
}
}
}
If the alert appears immediately you may try to change the cache policy to
.reloadIgnoringCacheData
I don't know exactly why this error occurs but I have also faced this error, so I have put one solution. This error has some unique error code. So check that error code and ignore alert over there or you can again try this API call if this error code you get.
I find one solution to this issue if you using Alamofire.
First import Alamofire in your common class otherwise you can create a separate class for check internet connection.
import Alamofire
class Connectivity {
class func isConnectedToInternet() ->Bool {
return NetworkReachabilityManager()!.isReachable
}
}
Call below method before you API call
if !Connectivity.isConnectedToInternet() {
ServiceHandler.ShowAlert(message: "Check your internet connectivity.", title: "Error", parentView: self) //This is my comman method for display alert.
return
}

Postman giving different response

I am a beginner in swift iOS and I am doing login module of an application in iOS but I am stuck at one thing I have login api but when I am checking response in postman when I am sending parameters as "raw" than it is showing user logged in but when I am sending the same parameters as "form-data" than it is showing wrong id and password....can anyone tell me how to send parameters as "raw" so that I can get correct response?? Thanks for your help!!
Please try this method if you are using Alamofire library for API call.
func request(_ method: HTTPMethod
, _ URLString: String
, parameters: [String : AnyObject]? = [:]
, headers: [String : String]? = [:]
, onView: UIView?, vc: UIViewController, 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)
}
}
}
Also remember you need to pass Application/JSON header while calling this method.
["Content-Type": "application/json"]
From: http://toolsqa.com/postman/post-request-in-postman/
Check if your raw is using the correct format type as specified below.

Code will run in playground, but fails when executed in application simulator

I am attempting to get the HTML of a URL with the NSURL function. The code runs well and the HTML is properly returned when executed from the playground, however when I implement it into a button from the storyboard the app crashes. I changed the App Transport Security in the Info.plist file, however I am still encountering a crash. Here is my Info.plist: http://imgur.com/a/BB3KF. The error message also says that there is a nil value, however I have tested the variables in the function and everything seems to be != nil.
Playground code:
let myUrl = NSURL(string: "http://www.google.com")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
self.testLabel.text = "\(responseString)"
if error != nil {
print("Error: \(error)")
}
}
task.resume()
XCode code:
import UIKit
import Foundation
class ViewController: UIViewController {
#IBOutlet weak var testLabel: UILabel!
#IBAction func testButton(sender: UIButton) {
let myUrl = NSURL(string: "http://www.google.com")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
self.testLabel.text = "\(responseString)"
if error != nil {
print("Error: \(error)")
}
}
task.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Error message:
2015-10-29 10:20:36.127 testProject[1263:49414] App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
The error occurs because iOS9 connections to the servers must be secure (https ) to allow the use of http add the following into info.plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
You need to set the NSAppTransportSecurity value in info.plist as the following:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>localhost</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
</dict>
</dict>
change localhost to your actual server
App Transport Security has blocked a cleartext HTTP resource

Resources