【发布时间】:2014-06-03 16:46:32
【问题描述】:
我正在从另一个应用程序中启动一个应用程序并传递一个值。我可以将值放入 AppDelegate,但似乎无法从 ViewController 访问它。这是我正在使用的代码:
来自 App 1(在按钮触摸时调用):
NSString* str360URL = @"customer360://?customerNum=70044321";
BOOL canOpenURL = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:str360URL]];
if (canOpenURL) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:str360URL]];
}
来自 App 2 AppDelegate:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
if ([[url scheme] isEqualToString:@"customer360"]) {
//check to see if we are passing in a customer number
if ([[url query] rangeOfString:@"customerNum"].location != NSNotFound) {
//get all the query string items (there should be only the customer num as of 6/01/14 but just in case they want to expand what is passed in
NSArray* arrQueryComponents = [[url query] componentsSeparatedByString:@"&"];
//loop
for(NSString* strThisKVPair in arrQueryComponents) {
//split the kv pairs into parts
NSArray* arrKVPair = [strThisKVPair componentsSeparatedByString:@"="];
//get the value from the kv pair
self.strCustomerNum = [arrKVPair objectAtIndex:1];
}
}
...
这里有更多用于注册的代码。我可以在这里弹出一个 UIAlertView 并查看属性 self.strCustomerNum 上的正确值,所以我知道 appDelegate 将它存储在它的属性中。
在 ViewController 我有这个代码:
//pass in the customer number
self.strCustomerNum = ((AppDelegate *)[UIApplication sharedApplication].delegate).strCustomerNum;
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"App View Controller" message:self.strCustomerNum delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
[alert show];
但我的警报没有显示客户编号。正在导入 AppDelegate.h。关于我在哪里出错的任何想法?
【问题讨论】:
-
如何/何时调用视图控制器中的代码?可能在
application:openURL:sourceApplication:annotation:中的代码执行之前创建了警报视图 -
我已经解决了——这就是问题所在——如果它在后台运行,则 viewDidLoad 方法已经运行。我正在从另一种运行通知的方法访问它并且它有效。但是,如果您在答案中发表评论,我会给您功劳。
-
完成。很高兴你找到了解决方案:)
标签: ios uiviewcontroller appdelegate