现象
对着书本及网上文章,如果要进行真机调试,得修改appdelegate.m里的ip,但高版本的react native已经做了大变动。
React Native iOS在0.29.0版本中BundleURL加载方法做了重大改变,新增了RCTBundleURLProvider单例类专门处理BundleURL,使用NSUserDefaults保存配置信息。
默认加载方式
在Debug模式下,执行react-native-xcode.sh编译脚本会自动获取当前网卡en0的IP地址,并打入App包中一个配置文件ip.txt,App运行时会读取ip文件,自动生成Developer Server URL,通过这种加载方式,我们不再需要手动去把”localhost”改成Mac的IP了,每次编译都会读取当前最新的IP。
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@”index.ios” fallbackResource:nil];
解决方法
手动设置IP
RCTBundleURLProvider在接口中暴露了jsLocation属性,可以通过setJsLocation手动设置IP。
NSURL *jsCodeLocation;
[[RCTBundleURLProvider sharedSettings] setDefaults];
if DEBUG
[[RCTBundleURLProvider sharedSettings] setJsLocation:@”192.168.3.13”];
endif
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@”index.ios” fallbackResource:nil];
另需要在Info设置NSAppTransportSecurity的NSAllowsArbitraryLoads为true即可。
总之
RCTBundleURLProvider类做了一些消息和属性的封装,可以通过判断是否DEBUG环境然后做不同的设置。