react-native 调试时怎么实现设备可以访问电脑IP的bundle资源的?

954 阅读1分钟

一、分析XcodeBuild 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文件里

三、断点分析获取过程

RCTBundleURLProviderguessPackagerHost 方法里读取了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拼接方法细节