How to get current computer's IP address in Xcode

后端 未结 3 1828
不思量自难忘°
不思量自难忘° 2021-02-08 17:57

When testing iPhone apps that connect to my local machine\'s server, I need to enter my computer\'s local IP address as opposed to localhost in order to test with d

3条回答
  •  醉酒成梦
    2021-02-08 18:06

    I got this working by having a run script set the computer's IP address in the app's plist, then reading the plist value in code.

    1) In your Info.plist file, add a key/value pair that will contain your computer's IP address. For this example, we'll add a key of "CompanyNameDevServerIP", of type "String". Note that this key/value pair should be prefixed uniquely, so that it doesn't conflict with Apple's keys (see here for more info).

    2) In the "Build Phases" tab, add a run script that contains the following:

    if [ "$CONFIGURATION" == "Debug" ]; then
      echo -n ${TARGET_BUILD_DIR}/${INFOPLIST_PATH} | xargs -0 /usr/libexec/PlistBuddy -c "Set :CompanyNameDevServerIP `ipconfig getifaddr en0`"
    else
      echo -n ${TARGET_BUILD_DIR}/${INFOPLIST_PATH} | xargs -0 /usr/libexec/PlistBuddy -c "Delete :CompanyNameDevServerIP"
    fi
    

    This sets the computer's IP address in the plist that gets bundled with the build, but only in debug builds. (It's removed from the plist file in release builds.)

    • Hat tip to this blog post for providing this technique.
    • You may need to use a different interface other than en0 (see here for more info).

    3) In code, retrieve this plist value to get your computer's IP address:

    NSString *serverIP = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CompanyNameDevServerIP"];
    

提交回复
热议问题