How to get current computer's IP address in Xcode

后端 未结 3 1827
不思量自难忘°
不思量自难忘° 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:23

    1) Add a "Run Script" in the "Build Phases" tab of your Xcode project that contains this:

    export SERVER_IP=`ipconfig getifaddr en0`
    

    Note: change "en0" to whichever interface matches your machine. en0 is the wifi on my machine and my hard-wire is en3. Do an "ifconfig -a" in Terminal to get the list of all of your adapters and see which is which for your machine

    2) Go to your project file. Click the Project itself in the left menu then Build Settings in the right side. Go to "Apple LLVM 6.0 - Custom Compiler Flags". Under "Other C Flags" -> "Debug" define a new value called -DSERVER_IP=${SERVER_IP}

    This will map your build script's results into a #DEFINE in your project

    3) In your code use SERVER_IP just like you would any other #DEFINE and it will always have the value of the computer that built the code.

提交回复
热议问题