Ios simulator access to local server
I am trying to get vacation data in ios app and I am using this code:
var rest_url = "http://192.168.0.1:8000/rest/users/"
let url: NSURL = NSURL(string: rest_url)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
if(error != nil) {
println(error.localizedDescription)
}
println(data)
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary!
But i think i cant access my server like this, does anyone know how i can access my server from ios simulator?
source to share
Do you have application transport security settings in your Info.plist file? If not, then for debugging purposes you can set them like
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
These settings allow you to issue requests to any server. But don't do this for the production version. It's not safe.
source to share
Maybe you can replace 192.168.0.1 with localhost when debugging with the ios simulator (i.e. real devices should use your server's IP).
I also cannot access my test server using the IP on the simulator. But when I use localhost or 120.0.0.1 the simulator can work well with my test server.
source to share
If you have a server running on a computer that is running the iOS simulator, you need to select " http://127.0.0.1 " as the URL.
In your case, it would be:
var rest_url = "http://127.0.0.1:8000/rest/users/"
source to share
For people who find this thread due to not being able to connect to localhost due to invalid certificate: in yours, URLSessionDelegate
you have to answer with the URLAuthenticationChallenge
following delegate method:
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { func defaultAction() { completionHandler(.performDefaultHandling, nil) } // Due to localhost using an invalid certificate, we need to manually accept it and move on guard challenge.protectionSpace.host.hasPrefix("localhost") else { return defaultAction() } guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust else { return defaultAction() } guard let trust = challenge.protectionSpace.serverTrust else { return defaultAction() } completionHandler(.useCredential, URLCredential(trust: trust)) }
source to share