简体   繁体   中英

Objective-c: Pass value from AppDelegate to UIViewController

I am launching an app from within another app and passing a value. I can get the value into the AppDelegate but I can't seem to access it from the ViewController. Here's the code I am using:

From App 1 (gets called on button touch):

NSString* str360URL = @"customer360://?customerNum=70044321";

    BOOL canOpenURL = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:str360URL]];

    if (canOpenURL) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str360URL]];
    }

From 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];

            }

        }
...

There's more code in here for registration purposes. I can pop up a UIAlertView here and see the correct value on the property self.strCustomerNum, so I know appDelegate is storing it in its properties.

In ViewController I have this code:

//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];

My alert doesn't show the customer number though. AppDelegate.h is being imported. Any thoughts on where I am going wrong here?

My best guess is that the code in your view controller is executed before the code in your app delegate, so the value of strCustomerNum is nil.

You can confirm this by setting breakpoints in your view controller and in your app delegate's application:openURL:sourceApplication:annotation:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM