我正在尝试集成"Open with…"功能。
在我的AppDelegate.m
中,我有
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
...
_fileContent = [NSString stringWithContentsOfURL:url
encoding:NSUTF8StringEncoding
error:&error];
...
ViewController *vc = (ViewController*)self.window.rootViewController;
[vc refreshUI:nil];
}
我正在使用ARC,所以我只在ViewController.h
中调用以下内容,稍后在.m
中省略@synthesize
@property (nonatomic, retain) IBOutlet UITextView *textView;
在我的ViewController.m
中,我有以下
-(void)refreshUI:(id)sender
{
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
if ([appDelegate openedFromURL])
{
NSLog(@"[refreshUI] appDelegate openFromURL (Length: %d)", [appDelegate.fileContent length]);
NSLog(@"Contents before: %@", [_textView text]);
[_textView setText:appDelegate.fileContent];
NSLog(@"Contents after: %@", [_textView text]);
}
...
}
当我从另一个应用程序(Dropbox)打开我的文件时,第一个NSLog会给我正确的文件长度。第二个NSLog为我提供了UITextView的正确"旧"内容,第三个NSLog给我提供了正确的"新"内容(从我通过dropbox应用程序"打开…"的文件的内容开始)。所以这些数据确实进入了我的应用程序。
问题是UITextView没有得到更新。如果我按下UIViewController中的任何其他按钮(这会导致我切换到另一个UIViewController),然后返回"ViewController",则UITextView将用正确的数据更新。即使我向添加了UIButton并将其操作设置为仅调用[self refreshUI]
,UITextView也会更新。
它只是不会从AppDelegate调用的方法中自行刷新。
我做错了什么?我甚至尝试用setNeedsDisplay
手动重新绘制UITextView。但这并没有起到任何作用。
感谢
As现在可以从您的注释中推导出来。你的故事板片段似乎是在实例化你的"ViewController"类的一个新实例,而不是让你回到原来的实例。然而,原始的仍然是应用程序代理的rootViewController
。这将导致您向视图控制器的实例发送消息,而该实例不是当前呈现的实例。本质上,你是在改变一个你看不见的标签。有几种方法可以解决这个问题。
- 更改分段,以便它们将您带回
rootViewController
:
这可能是最简单的,可能会提高你的效率。在导致返回的方法中,使用带有pop...
或dismiss
之类单词的方法。
- 使用委派:
向应用程序代理添加urlLaunchDelegate
,并在适当的时间(viewDidLoad
或viewWillAppear:
)将视图控制器设置为urlLaunchDelegate
。
- 使用
NSNotificationCenter
您的视图控制器观察到一个类似MyApplication_LaunchURLNotification
的通知。您可以添加NSURL
作为对象。
@property (nonatomic, retain) IBOutlet UITextView
需要声明一个名称
@property (nonatomic, retain) IBOutlet UITextView *textView
您还需要链接IBOutlet中的textView。