我尝试使用以下代码连接到我在Mac上本地运行的ruby sinatra服务器:
func load(finished: @escaping ()->()) {
// Create destination URL
let destinationFileUrl = documentsUrl.appendingPathComponent("Images.zip")
//Create URL to the source file you want to download
let fileURL = URL(string: "http://waynerumble.local~waynerumble:4567/download")
//Create Session
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url:fileURL!)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
finished()
} else {
print("Error took place while downloading a file. Error description: %@", (error?.localizedDescription)! as String);
finished()
}
}
task.resume()
}
如果我从模拟器测试应用程序并将fileURL
设置为"http://127.0.0.1:4567/download"
它可以正常工作但我从设备上了解到目前为止我必须尝试不同之处:
从终端中运行ifconig我在en1获得192.168.1.254
所以我尝试"http://192.168.1.255:4567/download"
给了我:
[] nw_socket_connect connectx failed: [13] Permission denied
Error took place while downloading a file. Error description: %@ Could not connect to the server.
我也尝试过:
"http://waynerumble.local:4567/download"
给出:
Error took place while downloading a file. Error description: %@ Could not connect to the server.
"http://waynerumble.local.~waynerumble:4567/download"
(waynerumble是我的计算机名和用户名),它给出了:
Error took place while downloading a file. Error description: %@ A server with the specified hostname could not be found.
我也有以太网和iphone的wifi上网共享。我不知道还有什么可以尝试
答案 0 :(得分:1)
192.168.1.255
是您网络的brodcast地址,您不应该使用它。
为什么不连接到真实的IP 192.168.1.254
?
要将Sinatra应用程序绑定到每个界面,请尝试:
class MyApp < Sinatra::Base
set :bind, '0.0.0.0'
然后http://192.168.1.254:4567/download
应该有效。
还要记住在防火墙中打开所需的端口。