iOS模拟器访问本地主机服务器

14

我正在尝试将REST数据传输到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模拟器访问我的服务器吗?


2
本地主机是 127.0.0.1。您的 Web 服务器可能仅在该 IP 上侦听。 - B.R.W.
The operation couldn’t be completed. (NSURLErrorDomain error -1004.) <> JSON Error The operation couldn’t be completed. (Cocoa error 3840.) fatal error: unexpectedly found nil while unwrapping an Optional value - Mirza Delic
5个回答

7

您的Info.plist文件中是否有App Transport Security设置? 如果没有,为了调试目的,您可以像下面这样设置:

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

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


6

确保您的Mac IP地址为192.168.0.1。因此,您的网址可能是

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

我在192.168.0.13上使用8000端口运行Python服务器,我尝试了那个URL和127.0.0.1:8000,但都不起作用 :/ “操作无法完成。(NSURLErrorDomain错误-1004。)<> JSON错误操作无法完成。(Cocoa错误3840。)致命错误:在解包可选值时意外发现nil” - Mirza Delic

4
如果您在运行 iOS 模拟器的计算机上有一台服务器,则需要选择'http://127.0.0.1'作为 URL。在您的情况下,URL 将是:
var rest_url = "http://127.0.0.1:8000/rest/users/"

3

如果您因为无效证书无法连接到本地主机,可以参考以下方法:在您的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))
}

1
也许你可以在使用iOS模拟器进行调试时,将192.168.0.1替换为localhost(即,实际设备应使用你的服务器IP)。我无法通过模拟器使用IP地址访问我的测试服务器。但是,当我使用localhost或120.0.0.1时,模拟器可以与我的测试服务器良好地配合工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接