Can't connect php file with Xcode through iPho

2019-09-06 03:32发布

问题:

I am working on an app which includes a database. I use PHP to connect to a MySQl database. Here is my connection code:

var request = URLRequest(url: URL(string: "http://localhost/Workspace/Twitter/register.php")!)
request.httpMethod = "POST"
let body = "Username=\(UsernameTXF.text!.lowercased())&password=\(PassTXT.text!.lowercased())"
request.httpBody = body.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else {                                                 // check for fundamental networking error
     print("error=\(error)")
     return
}

This code works flawlessly when I run it on simulator,but when I run it on iPhone it gives me following error:

error=Optional(Error Domain=NSURLErrorDomain Code=-1004 "Could not connect to the server." UserInfo={NSUnderlyingError=0x17425dbb0 {Error Domain=kCFErrorDomainCFNetwork Code=-1004 "(null)" UserInfo={_kCFStreamErrorCodeKey=61, _kCFStreamErrorDomainKey=1}}, NSErrorFailingURLStringKey=http://localhost/Workspace/Twitter/register.php, NSErrorFailingURLKey=http://localhost/Workspace/Twitter/register.php, _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=61, NSLocalizedDescription=Could not connect to the server.})

回答1:

"localhost" on your iPhone is an entirely different thing than "localhost" on your desktop running a simulator. If you want to run this code on your iPhone, specify a domain that can be reached from the phone. I.e., use a numeric IP address or specify a domain where your web service is running.