如何在Xcode的Swift项目中访问localhost本地服务器并测试连通性
解决Xcode Swift项目访问本地localhost服务器的方案
当前代码的核心问题
checkResourceIsReachable()方法仅适用于检测本地文件系统的资源是否存在,不支持检测网络URL的连通性,这是测试失败的首要原因。
常见配置坑排查
- 运行目标适配:
- 若使用iOS模拟器:可以直接用
http://localhost:4001/hello,也可以填写Mac的局域网IP - 若使用iOS真机:需保证手机和Mac连接同一WiFi,填写Mac在该局域网下的实际IP(格式如192.168.3.xx),同时关闭Mac防火墙对4001端口的拦截
- 若开发的是macOS端Swift应用:需要在项目的「Signing & Capabilities」标签页中,勾选「App Sandbox」下的
Outgoing Connections (Client)权限,否则所有网络请求都会被沙盒拦截
- 若使用iOS模拟器:可以直接用
- ATS权限配置:
苹果默认禁止App发送明文HTTP请求,你需要在项目的Info.plist中添加配置放开本地HTTP请求限制:右键点击Info.plist选择「Open As -> Source Code」,将以下内容粘贴到<dict>标签内部即可:<key>NSAppTransportSecurity</key> <dict> <key>NSExceptionDomains</key> <dict> <key>localhost</key> <dict> <key>NSIncludesSubdomains</key> <true/> <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key> <true/> </dict> </dict> </dict>
正确的连通性测试代码
使用URLSession发起简单GET请求即可验证连通性,示例代码如下:
// 必须带上http://前缀,否则URL构造会失败 let urlString = "http://localhost:4001/hello" guard let url = URL(string: urlString) else { print("URL格式错误") return } let task = URLSession.shared.dataTask(with: url) { _, response, error in DispatchQueue.main.async { if let error = error { print("连通失败,错误:\(error.localizedDescription)") return } guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else { print("连通失败,服务端返回非成功状态码") return } print("Success! 服务端连通正常") } } task.resume()
内容的提问来源于stack exchange,提问作者John Sorensen
相关产品推荐
相关产品推荐

