ios模拟器访问localhost服务器

时间:2014-09-06 16:31:21

标签: ios swift localhost nsurlsession

我正在尝试将休息数据提供给ios应用程序,我使用此代码:

    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!

但我认为我无法像这样访问我的服务器,任何人都知道如何从ios模拟器访问我的服务器?

5 个答案:

答案 0 :(得分:3)

确保您的Mac IP为192.168.0.1。所以你的网址可能是

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

答案 1 :(得分:3)

您的Info.plist文件中是否有应用传输安全设置? 如果没有,那么出于调试目的,您可以将它们设置为

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

此类设置允许向任何服务器发出请求。 但是不要为发布版本这样做。这是不安全的。

答案 2 :(得分:1)

对于那些由于无效证书而无法连接到本地主机的用户而找到此线程的人:在您的URLSessionDelegate中,您应该使用以下委托方法来响应URLAuthenticationChallenge

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))
}

答案 3 :(得分:0)

使用ios模拟器进行调试时,可能是你可以用localhost替换192.168.0.1(也就是说,真实设备应该使用服务器的IP)。

我也无法在模拟器上使用IP地址访问我的测试服务器。但是当我使用localhost或120.0.0.1时,模拟器可以很好地与我的测试服务器配合使用。

答案 4 :(得分:0)

如果您的服务器在运行iOS模拟器的计算机上运行,​​则需要选择“ http://127.0.0.1”作为URL。

您的情况将是:

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