React-Native频繁修改IP,烦吗
React-Native 开发中,从模拟器切换到真机你必须要做的是:打开AppDelegate.m,将 #if TARGET_OS_SIMULATOR
jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"];
#else
#warning "DEBUG DEVICE"
NSString *serverIP = 【你的IP】;
NSString *jsCodeUrlString = [NSString stringWithFormat:@"http://%@:8081/index.ios.bundle?platform=ios&dev=true",serverIP];
jsCodeLocation = [NSURL URLWithString:jsCodeUrlString];
#endif
这样,就完成了。但是如果是 release 的话想使用打包的文件咋办? 我们可以直接判断:如果是在 debug 下的话就是用上面的代码,否则则是用 bundle,如下: #if DEBUG
#if TARGET_OS_SIMULATOR
#warning "DEBUG SIMULATOR"
jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"];
#else
#warning "DEBUG DEVICE"
NSString *serverIP = 【你的IP】;
NSString *jsCodeUrlString = [NSString stringWithFormat:@"http://%@:8081/index.ios.bundle?platform=ios&dev=true",serverIP];
jsCodeLocation = [NSURL URLWithString:jsCodeUrlString];
#endif
#else
//release
jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
这样,我们就能在 debug 和 release 都不用修改代码了。但是,有个问题,这个【你的IP】很是碍眼啊,公司和家里的 IP 肯定不一样啊,不还是得改。而且如果将这代码 push 到服务器,其他人也还是要改,根本问题还是不能解决。如果我们能动态获取到计算机的 IP 问题就解决了。是的,接下来我们要做的就是这个,在终端上获取 IP 的命令是(Linux和Mac OS): 然后粘贴如下代码将获取到的 IP 写入到 plist 文件中。 INFOPLIST="${TARGET_BUILD_DIR}/${INFOPLIST_PATH}"
echo "writing to $INFOPLIST"
PLISTCMD="Add :SERVER_IP string $(ifconfig | grep inet | tail -1 | cut -d " " -f 2)"
echo -n "$INFOPLIST" | xargs -0 /usr/libexec/PlistBuddy -c "$PLISTCMD" || true
PLISTCMD="Set :SERVER_IP $(ifconfig | grep inet | tail -1 | cut -d " " -f 2)"
echo -n "$INFOPLIST" | xargs -0 /usr/libexec/PlistBuddy -c "$PLISTCMD" || true
这样,每次编译程序的时候就会将 IP 写入到 plist 文件了。 NSString *serverIP = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"SERVER_IP"];
到这,基本就完成了。但是还有个问题:如果我们还想在真机上运行并且在 Chrome 上进行 Debug,那我们还需修改一下 RCTWebSocketExecutor.m 这个文件。将这个文件的 init 方法替换成一下代码即可: - (instancetype)init
{
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
NSInteger port = [standardDefaults integerForKey:@"websocket-executor-port"] ?: 8081;
#if TARGET_OS_SIMULATOR
NSString *URLString = [NSString stringWithFormat:@"http://localhost:%zd/debugger-proxy",port];
#else
NSString *serverIP = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"SERVER_IP"];
NSString *URLString = [NSString stringWithFormat:@"http://%@:%zd/debugger-proxy",serverIP,port];
#endif
return [self initWithURL:[RCTConvert NSURL:URLString]];
}
总结通过判断当前运行设备的宏以及编译时通过脚本将 IP 写入 plist 文件我们就可以实现动态的设置 IP 了,以后我们就不需要反复修改 IP 了。另外,通过 补充通过这些天的实践,出现了一个问题,有时候用 参考资料: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |