【问题标题】:How do I handle a Custom URL Scheme in PhoneGap for a cold start?如何在 PhoneGap 中处理自定义 URL 方案以进行冷启动?
【发布时间】:2013-09-02 03:35:57
【问题描述】:

我将 handleOpenURL() 用于自定义 URL 方案,以从电子邮件中的链接启动我的应用程序。完美运行,我可以根据链接中的 URL 参数在我的应用中做一些事情。

问题是当我的应用程序进行冷启动(不在后台运行)时,handleOpenURL() 似乎没有被调用。是否有其他处理程序可用于冷启动与已经运行的实例?

是否有一个我可以读取的全局变量来告诉我调用 URL 是什么?我读过关于invokeString,但似乎从未设置过?

我正在使用 PhoneGap 2.0

【问题讨论】:

  • 在cordova 3.5 中遇到了同样的问题(是的,几年过去了,我想它在某些版本中已修复)。现在 iOS 弃用了 handleOpenUrl 等,但下面的有效答案仍然可以工作。

标签: cordova


【解决方案1】:

如果你仔细阅读 application:handleOpenURL 方法上面的注释,你可能会明白:

// this happens while we are running ( in the background, or from within our own app )
// only valid if Calinda-Info.plist specifies a protocol to handle
- (BOOL) application:(UIApplication*)application handleOpenURL:(NSURL*)url

如果应用程序未运行,则不会调用此方法。我的解决方案是通过以下更改来调整项目:

MainViewController.h

@interface MainViewController : CDVViewController
@property (nonatomic, retain) NSString *URLToHandle;
@end

MainViewController.m

- (void) webViewDidFinishLoad:(UIWebView*) theWebView 
{
     if (self.URLToHandle)
     {         
         NSString* jsString = [NSString stringWithFormat:@"window.setTimeout(function() {handleOpenURL(\"%@\"); },1);", self.URLToHandle];
         [theWebView stringByEvaluatingJavaScriptFromString:jsString];
     }
     [...]
}

- (void)dealloc
{
    self.URLToHandle = nil;
    [super dealloc];
}

@synthesize URLToHandle;

AppDelegate.m

- (BOOL) application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{   
    [...]
    self.viewController = [[[MainViewController alloc] init] autorelease];
    self.viewController.useSplashScreen = YES;
    self.viewController.wwwFolderName = @"www";
    self.viewController.startPage = @"index.html";
    self.viewController.view.frame = viewBounds;

    // Patch for handleOpenURL
    ((MainViewController *)self.viewController).URLToHandle = URLToHandle;

    [...]
}

希望对您有所帮助。

西里尔

附加说明:测试时请确保停止 xcode。当 xcode 运行时,应用程序会抛出异常。如果我停止 xcode,这个解决方案可以正常工作。

【讨论】:

  • 我在使用此解决方案的 AppDelegate.m 中收到错误(“未声明的标识符:URLToHandle”)。知道为什么吗?
【解决方案2】:

顺便说一句,如果有人遇到这种情况,唯一缺少的是在 AppDelegate(.h 和 .m)中定义 URLToHandle,就像在 MainViewController 中定义一样。

您还必须将AppDelegate.m 中的分配从:

((MainViewController *)self.viewController).URLToHandle = URLToHandle;

到:

NSString* jsString = [NSString stringWithFormat:@"window.setTimeout(function() {handleOpenURL(\"%@\"); },1);", url];
((MainViewController *)self.viewController).URLToHandle = jsString;

您实际上必须将网址从AppDelegate 转移到MainViewController

setTimeout 很重要,否则它不起作用。

【讨论】:

  • 我无法让这个工作,你能否将最终代码 sn-p 放入 appdelegate 和 mvc 中。谢谢..
猜你喜欢
  • 2011-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 2014-07-30
  • 1970-01-01
  • 2012-01-02
相关资源
最近更新 更多