一、分析Xcode的Build Phases
二、研究脚本内容
在node_modules/react-native/scripts/react-native-xcode.sh里
# Enables iOS devices to get the IP address of the machine running Metro Bundler
if [[ "$CONFIGURATION" = *Debug* && ! "$PLATFORM_NAME" == *simulator ]]; then
IP=$(ipconfig getifaddr en0)
if [ -z "$IP" ]; then
IP=$(ipconfig getifaddr en1)
fi
if [ -z "$IP" ]; then
IP=$(ifconfig | grep 'inet ' | grep -v ' 127.' | grep -v ' 169.254.' |cut -d\ -f2 | awk 'NR==1{print $1}')
fi
echo "$IP" > "$DEST/ip.txt"
fi
在Debug或者模拟器时会把当前IP地址写入app里的ip.txt文件里
三、断点分析获取过程
RCTBundleURLProvider 的 guessPackagerHost 方法里读取了ip.txt文件的内容
- (NSString *)guessPackagerHost
{
static NSString *ipGuess;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSString *ipPath = [[NSBundle mainBundle] pathForResource:@"ip" ofType:@"txt"];
ipGuess = [[NSString stringWithContentsOfFile:ipPath encoding:NSUTF8StringEncoding error:nil]
stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
});
NSString *host = ipGuess ?: @"localhost";
if ([self isPackagerRunning:host]) {
return host;
}
return nil;
}
在guessPackagerHost方法打断点可以进一步分析URL拼接方法细节