React Native 0.29.0版本iOS端BundleURL加载方法

React Native iOS在0.29.0版本中BundleURL加载方法作了重大改变,新增了RCTBundleURLProvider单例类专门处理BundleURL,使用NSUserDefaults保存配置信息。react

默认加载方式

在Debug模式下,执行react-native-xcode.sh编译脚本会自动获取当前网卡en0的IP地址,并打入App包中一个配置文件ip.txt,App运行时会读取ip文件,自动生成Developer Server URL,经过这种加载方式,咱们再也不须要手动去把"localhost"改为Mac的IP了,每次编译都会读取当前最新的IP。ios

if [[ "$CONFIGURATION" = "Debug" && "$PLATFORM_NAME" != "iphonesimulator" ]]; then
  PLISTBUDDY='/usr/libexec/PlistBuddy'
  PLIST=$TARGET_BUILD_DIR/$INFOPLIST_PATH
  IP=$(ipconfig getifaddr en0)
  $PLISTBUDDY -c "Add NSAppTransportSecurity:NSExceptionDomains:localhost:NSTemporaryExceptionAllowsInsecureHTTPLoads bool true" $PLIST
  $PLISTBUDDY -c "Add NSAppTransportSecurity:NSExceptionDomains:$IP.xip.io:NSTemporaryExceptionAllowsInsecureHTTPLoads bool true" $PLIST
  echo "$IP.xip.io" > "$DEST/ip.txt"
fi

非Debug模式时,没有ip.txt文件,会直接读取本地jsbundle文件,和之前版本的Load from pre-bundled file on disk方式相同。
可是我通过测试发现,en0是Wifi的网络,若是关闭Wifi,使用网线端口链接网络,en0默认就是inactive,没有对应的IP。react-native

手动设置IP

RCTBundleURLProvider在接口中暴露了jsLocation属性,能够经过setJsLocation手动设置IP。xcode

NSURL *jsCodeLocation;

[[RCTBundleURLProvider sharedSettings] setDefaults];
#if DEBUG
[[RCTBundleURLProvider sharedSettings] setJsLocation:@"192.168.1.101"];
#endif
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];

另须要在Info设置NSAppTransportSecurityNSAllowsArbitraryLoadstrue便可。网络

总之

RCTBundleURLProvider类作了一些消息和属性的封装,能够经过判断是否DEBUG环境而后作不一样的设置。iphone

相关文章
相关标签/搜索