Flutter中如何打开以itms-apps开头的链接?
问题原因
iOS 9及以上版本对应用跳转的外部Scheme做了白名单限制,未在Info.plist中登记的Scheme,调用canLaunch会直接返回false,导致跳转逻辑无法执行。
解决方案
1. 配置iOS白名单
打开iOS项目下的ios/Runner/Info.plist文件,添加如下配置:
<key>LSApplicationQueriesSchemes</key> <array> <string>itms-apps</string> <!-- 可在此处添加其他你用到的Scheme,如mailto、tel等 --> </array>
2. 优化跳转逻辑
增加降级兼容逻辑,当itms-apps协议跳转失败时,自动替换为https协议的App Store链接重试,同时捕获异常避免应用崩溃。
如果使用的是url_launcher 6.0.0以下版本,可使用如下代码:
_launchURL(String _url) async { try { bool canLaunchValid = await canLaunch(_url); if (canLaunchValid) { await launch(_url); } else { // itms-apps跳转失败时降级为https协议跳转 if (_url.startsWith('itms-apps://')) { String httpsUrl = _url.replaceFirst('itms-apps://', 'https://'); if (await canLaunch(httpsUrl)) { await launch(httpsUrl); return; } } throw 'Could not launch $_url'; } } catch (e) { print('跳转失败: $e'); } }
如果使用的是url_launcher 6.0.0及以上版本,原canLaunch、launchAPI已废弃,建议使用新API:
import 'package:url_launcher/url_launcher.dart'; _launchURL(String urlStr) async { final Uri targetUrl = Uri.parse(urlStr); try { if (await canLaunchUrl(targetUrl)) { await launchUrl(targetUrl); } else { // 降级兼容逻辑 if (targetUrl.scheme == 'itms-apps') { final Uri httpsUrl = Uri.https(targetUrl.host, targetUrl.path); if (await canLaunchUrl(httpsUrl)) { await launchUrl(httpsUrl); return; } } throw 'Could not launch $urlStr'; } } catch (e) { print('跳转失败: $e'); } }
3. 测试注意事项
itms-apps协议对应App Store应用,iOS模拟器没有内置App Store,因此必须在真实iOS设备上测试跳转逻辑。
内容的提问来源于stack exchange,提问作者Rajesh2701
相关产品推荐
相关产品推荐

