我面临一个奇怪的问题。
我正在使用 xcode 7.2、iOS 9,在真实设备 iphone 4S(不是模拟器)上工作。
我有 2 个应用程序,app1 和 app2。 app1 应该使用 url 方案将数据发送到 app2。
app2已经很好地声明了该方案
app1 已引用 plist 中的方案(因为 iOS9 中需要)
<key>LSApplicationQueriesSchemes</key>
<array>
<array>
<string>OpenLinkMyData</string>
</array>
</array>
这是我使用的代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0) , ^{
// build the url, using the scheme name, and the data
// note that json is escaped from bad url chars.
NSString * MyJsonDataWellEscaped = [[SomeClass getJSonDataToExport] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL * url = [NSURL URLWithString:[NSString stringWithFormat:@"OpenLinkMyData://%@",MyJsonDataWellEscaped]];
// Next line should allow test if the app able to manage that scheme is installed.
// BUT in our case, this allways returning false.
bool can = [[UIApplication sharedApplication] canOpenURL:url];
NSLog(@"canOpenUrl = %@", can?@"true":@"false");
});
// code of the app that do stuff...
}
我得到以下日志:
-canOpenURL:URL 失败:“OpenLinkMyData://(myJsonSuff)” - 错误:“不允许此应用程序查询方案 OpenLinkMyData”
可以打开网址 = false
但如果我使用以下代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0) , ^{
// build the url, using the scheme name, and the data
// not that json is escaped from bad url chars.
NSString * MyJsonDataWellEscaped = [[Move2MyMHelper getJSonDataToExport] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL * url = [NSURL URLWithString:[NSString stringWithFormat:@"OpenLinkMyData://%@",MyJsonDataWellEscaped]];
if([[UIApplication sharedApplication] openURL:url])
{
NSLog(@"App launched OK");
}
else
{
NSLog(@"App not launched");
}
});
// code of the app that do stuff...
}
如果我不检查方案是否可用并直接使用它,App2 会很好地打开并根据需要获取所有数据。
(否则,如果未安装 app2,我会收到“应用程序未启动”日志)。
这是用于接收数据的 App2 源(按预期工作):
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
NSString *prefixToRemove = @"OpenLinkMyData://";
if(url != nil && [[url absoluteString] hasPrefix:prefixToRemove])
{
NSString * urlStr = [url absoluteString];
NSString * json = [urlStr substringFromIndex:[prefixToRemove length]];
json = [json stringByRemovingPercentEncoding];
NSLog(@"OpenLinkMyData with json : %@", json);
}
return YES;
}
我的情况下 canOpenUrl 有什么问题?
谢谢你的帮助。