Xcode - 我无法从AppDelegate运行整个方法

时间:2013-01-26 17:30:24

标签: objective-c xcode methods url-scheme appdelegate

我正在使用自定义网址方案来打开我的应用,然后获取链接并在方法中运行。但我无法真正运行这种方法。

例如,我无法加载网页视图或更改标签或文本字段。那么如何加载Web视图和更改标签?

AppDelegate.m

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {    
    if (!url) {  return NO; }
    NSString *URLopen= [[url host] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    ViewController *vc = [[ViewController alloc]init];
    vc.URLschemeLink = URLopen;
    [vc URLscheme];   
    return YES;
}

ViewController.h

@interface ViewController : UIViewController<MFMailComposeViewControllerDelegate> {
    NSString *URLschemeLink;
}

-(void)URLscheme;

@end

ViewController.m

@implementation ViewController
@synthesize URLschemeLink;

-(void)URLscheme {
    //for example:
    label.text = @"Hello"; //nothing will happen
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]]]; //Nothing will happen

    NSLog ("Method Works Perfect"); //will happen

    UIAlertView *alert = [[UIAlertView alloc]
                               initWithTitle:@"Title:"
                                     message:[NSString stringWithFormat:@"%@", URLSchemeLink]
                                    delegate:nil
                           cancelButtonTitle:@"OK"
                           otherButtonTitles:nil];
    [alert show];
    //UIAlertView will work perfectly and show the URLschemeLink from AppDelegate.
}

确定如何加载标签/ webview? 我测试从app delegate传递一个名为runURLscheme(= true)的bool。 然后我在ViewDidLoad中写道:

if(runURLscheme==true) {
    [self URLScheme];
}

但这不起作用,它不会运行URLscheme方法。 我怎样才能加载标签/网页?

1 个答案:

答案 0 :(得分:0)

与视图控制器关联的主视图通常是延迟加载的。仅仅因为视图控制器已初始化,并不意味着它已加载其主视图。只有在调用viewDidLoad后,您的观点才能安全访问。

一般来说,这种模式效果很好:

  • 独立于显示数据的任何视图存储您的数据。
  • 运行自定义URL方案时,请更新此数据。
  • 在视图控制器上有一个方法,可以根据此数据更新其视图。
  • viewDidLoad
  • 调用此方法

如果有可能在您的视图加载后更新此数据(例如,如果您从网络接收数据),则使用通知或KVO再次调用您的视图更新方法。