我试图让现有的 iOS 应用程序使用 React Native,因此我编写了手动桥接两者的代码,而不是使用提供的 CLI 工具。我希望 RCTBundleURLProvider
自动检测捆绑服务器的 IP 地址,就像在 CLI 工具生成的应用程序中一样。
最后,当我运行应用程序时:
react-native run-ios
react-native start --> the bundle server doesn't start automatically, which is strange
在模拟器或设备中加载 React Native bundle 时,出现错误No bundle URL present。
执行 clean/npm install/running react-native run-ios 没有帮助。直接在代码中设置 URL 是可行的,因此这不是防火墙/AppTransportSecurity 问题。
我错过了什么?
AppDelegate.m
- RCTBundleURLProvider
返回的 jsCodeLocation
等于 null
:
...
- (void) loadReact:(NSDictionary*) launchOptions {
NSURL *jsCodeLocation;
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
// this WORKS --> jsCodeLocation = [NSURL URLWithString:@"http://xxx.xxx.xxx.xxx:8081/index.bundle?platform=ios"];
NSLog(@"JSCodeLocation:%@",jsCodeLocation); // jsCodeLocation equals null
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:@"MyModule"
initialProperties:nil
launchOptions:launchOptions];
UIViewController *vc = [[UIViewController alloc] init];
vc.view = rootView;
rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.window.rootViewController = vc;
[self.window makeKeyAndVisible];
}
...
RCTBundleURLProvider.m
查找名为 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;
}
...
package.json
:
{
"name": "MyModule",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"react": "16.0.0",
"react-native": "0.51.0"
},
"devDependencies": {
"babel-jest": "21.2.0",
"babel-preset-react-native": "4.0.0",
"jest": "21.2.1",
"react-test-renderer": "16.0.0"
},
"jest": {
"preset": "react-native"
}
}
最佳答案
我打开了an issue前段时间在 React Native 上讲过。
这里有一些解决方案:
- 运行
react-native run-ios
- 出现错误时,运行
npm install
- 然后运行
react-native run-ios
再次
- 运行
添加
NSAllowsLocalNetworking
至info.plist
确保你有
127.0.0.1 localhost
在你的主机中杀死任何其他进程
sudo lsof -i :8081
, 然后kill -9 <PID>
删除
YOUR_PROJECT/ios/build/
然后react-native run-ios
再次
我希望这些解决方案之一能够解决您的问题。如果没有,您可以在 the issue 上找到更多选项。 .
关于ios - 自定义 React Native 项目中不存在捆绑 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47696377/