如何在Xcode中获取当前计算机的IP地址 [英] How to get current computer's IP address in Xcode
问题描述
在测试连接到本地计算机服务器的 iPhone 应用程序时,我需要输入计算机的本地 IP 地址而不是 localhost
,以便使用模拟器以外的设备进行测试.这对于动态 IP 地址和多个开发人员进行测试时会很烦人.是否有代码片段可以获取正在编译代码的计算机的 IP 地址,而不是应用程序运行所在设备的 IP 地址(最好使用 C 或 Objective-C,而不是 Swift)?>
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 devices other than the simulator. This gets annoying with dynamic IP addresses and when multiple developers are testing. Is there a code snippet that can get the IP address of the computer that is compiling code, and NOT the IP the address of the device that the application is running on (preferably in C or Objective-C, and not Swift)?
推荐答案
我通过让运行脚本在应用程序的 plist 中设置计算机的 IP 地址,然后在代码中读取 plist 值来实现此目的.
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) 在您的 Info.plist 文件中,添加将包含您计算机 IP 地址的键/值对.在本例中,我们将添加类型为CompanyNameDevServerIP"的键细绳".请注意,此键/值对应具有唯一前缀,以免与 Apple 的键冲突(请参阅 此处了解更多信息).
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) 在构建阶段"选项卡中,添加包含以下内容的运行脚本:
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
这会在与构建捆绑在一起的 plist 中设置计算机的 IP 地址,但仅在调试构建中.(它已从发布版本的 plist 文件中删除.)
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) 在代码中,检索此 plist 值以获取您计算机的 IP 地址:
NSString *serverIP = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CompanyNameDevServerIP"];
这篇关于如何在Xcode中获取当前计算机的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!