wdbwdb1
wdbwdb1

Reputation: 225

Swift embedded HTTP server connects on Mac but not on iPhone

I'm trying to get this embedded HTTP server https://github.com/grzegorzleszek/HTTPSwiftServer working on Xcode iOS iPhone and all I need it to do is host and return a string. It's very basic and only has one swift file. I had to comment the following two lines in the below method to get it to work because the top one would always return null, but it works fine and returns the string in web browser successfully when run on myMac console after the lines are disabled.

class func handler(_ request: CFHTTPMessage, fileHandle: FileHandle, server: HTTPServer) -> HTTPResponseHandler {
    let handler = HTTPResponseHandler()
    handler.fileHandle = fileHandle
    handler.requestURL = CFHTTPMessageCopyRequestURL(request)!.takeUnretainedValue() as URL
    handler.method = CFHTTPMessageCopyRequestMethod(request)!.takeUnretainedValue() as String


    //let bodyCFData = CFHTTPMessageCopyBody(request)!.takeRetainedValue()
    //handler.body = bodyCFData as Data


    return handler
}

I downloaded the example directly and it works fine on myMac, so in a separate working iOS app which normally works fine I took all the code put it into a swift class file except these following lines which went in viewDidAppear in a ViewController controlled by a separate class file .

let server = HTTPServer.sharedInstance
server.router = SimpleRouter()
server.start()
RunLoop.main.run()

I could not get it to connect successfully on the iPhone, and another server from GitHub I don't remember which one it was I was able to get working on a Mac but not on the iPhone either. Everything compiles and runs fine and the print log says server started on localhost:8080 but then no connection in the web browser, however it connected fine on the Mac and had the same print log message. Is there some type of permission needed or trick to get a server to work on iOS iPhone? My iOS, Mac OS and Xcode are current, but I am using a virtual Mac on VMWare, again the server in the myMac console does work though. I've already added allow arbitrary loads to the plist and can get unsecure HTTP string with URLSession no problem. Thanks for any help.

Upvotes: 3

Views: 1011

Answers (1)

rmaddy
rmaddy

Reputation: 318954

What URL are you entering into your browser? You can't use localhost:8080. You need to enter the hostname or IP address of your actual iPhone, not localhost.

localhost is "that" machine. It worked in the simulator because then localhost is your Mac and the browser on your Mac can connect to itself as localhost. But when the server is on your iPhone and you enter localhost into your browser on your Mac, the server is no longer on the Mac, it's on the iPhone.

Upvotes: 1

Related Questions