GCDWebServer: Unable to open home page when using real iPhone

690 views Asked by At

I have an old app using GCDWebUploader of GCDWebServer to upload files into the app. And I copy the implementation code into a new project.

The problem: in this new project, the home page of GCDWebServer could be opened in iOS Simulator but cannot connect in real iPhone.

Environment: Xcode 12.2, iOS 14 CocoaPods

It is weird since I got a worked app already. So I did some checks:

  • first, old app is worked. Means the home page could be opened.
  • all devices are under same wifi.
  • try to open http://192.168.1.5/ or http://192.168.1.5:80 in browser, safari said "Cannot open the page, because the server isn't responding", however I could ping 192.168.1.5 in terminal successfully.
  • restart my iPhone
  • compare info.plist between two projects

No result! Would you guys advice about what I missed, maybe some config in Xcode to allow HTTP communication or some capabilities to enable?

What in console:

[DEBUG] Did open IPv4 listening socket 3
[DEBUG] Did open IPv6 listening socket 4
[INFO] GCDWebUploader started on port 80 and reachable at http://192.168.1.5/
Visit http://192.168.1.5/ in your web browser

The code:

import GCDWebServer
import Foundation

class MyWebUploader {
    // move webuploader to outside of init func to fix app crash issue.
    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    lazy var webUploader = GCDWebUploader(uploadDirectory: self.documentsPath)
    
    func initWebUploader() -> String {
        var ipAddress = String()
        
        webUploader.start()
        webUploader.allowedFileExtensions = ["mp3", "aac", "m4a", "wav"]
        if webUploader.serverURL != nil {
            // retrieve IP address from URL
            let str = webUploader.serverURL!.absoluteString
            let start = str.index(str.startIndex, offsetBy: 7)
            let end = str.index(str.endIndex, offsetBy: -1)
            let range = start..<end
            let mySubstring = str[range]
            ipAddress = String(mySubstring)
            print("Visit \(webUploader.serverURL!) in your web browser")
        } else {
            ipAddress = "No Wifi connected"
        }
        return ipAddress
    }
    
    func stopWebUploader() {
        webUploader.stop()
    }
}
1

There are 1 answers

0
Zhou Haibo On BEST ANSWER

This issue is caused by the new permission in iOS 14 to find and connect to devices on your local network.

To fix it, we need to add following info in info.plist

    <key>NSLocalNetworkUsageDescription</key>
    <string>Reason for using Bonjour that the user can understand</string>
    <key>NSBonjourServices</key>
    <array>
        <string>_http._tcp</string>
        <string>_http._udp</string>
    </array>

More details please see NSNetServiceBrowser did not search with error -72008 on iOS 14