Mirza Delic
Mirza Delic

Reputation: 4349

iOS simulator access localhost server

I am trying to get rest data to iOS app, and I use:

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 can't access my server like this. Does anyone know how I can access my server from the iOS simulator?

Upvotes: 15

Views: 26398

Answers (5)

llch
llch

Reputation: 128

Maybe you can replace 192.168.0.1 with localhost, when debugging with iOS simulator (that is, real devices should use your server's IP).

I also cannot access my test server using IP address on simulator. But when I am using localhost or 120.0.0.1, the simulator can work well with my test server.

Upvotes: 1

Max Chuquimia
Max Chuquimia

Reputation: 7854

For people finding this thread because they can't connect to localhost due to an invalid certificate: in your URLSessionDelegate you should respond to the URLAuthenticationChallenge with the 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))
}

Upvotes: 3

Navid
Navid

Reputation: 394

If you have a server running on the machine where you iOS simulator is running, then you need to choose 'http://127.0.0.1' as the URL.

In your case it will be :

var rest_url = "http://127.0.0.1:8000/rest/users/"

Upvotes: 4

Dmitry A.
Dmitry A.

Reputation: 598

Do you have App Transport Security Settings in your Info.plist file? If no then for debugging purpose you can set them like

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>

Such settings allow issuing requests to any server. But don't do so for a release version. It is insecure.

Upvotes: 7

SFeng
SFeng

Reputation: 2276

Make sure that your IP of your Mac is 192.168.0.1. So your url could be

var rest_url = "http://YOUR MAC IP:8000/rest/users/"

Upvotes: 7

Related Questions