0

I need some help in passing data from AppDelegate to another controller which is a Table View Controller. In AppDelegate , i have a server response which i converted it to string. What i want is to pass that string to the another controller(Table View Controller) and display it to the Cell.

This my code in AppDelegate.m

    #import "AppDelegate.h"
    #import "ChildListViewController.h"


     @interface AppDelegate ()


    @end

    @implementation AppDelegate
    {
       #define URL2 @"http://192.168.1.166/bustracking/activation/validateActivationCode"
    //    NSMutableData *mutData;
    //    NSString *responseActCode;
    //    NSString *responseParentID;
    //    NSString *mess;
    }
    @synthesize responseActCode, responseParentID,mess,beaconID,Name,trackerID,lat,longi,Status,Image;

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        // Override point for customization after application launch.
        UIUserNotificationSettings *settings =[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];

        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        return YES;


    }

    //get device token
    - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
    {
        NSString *device = [deviceToken description];
        device = [device stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
        device = [device stringByReplacingOccurrencesOfString:@" " withString:@""];

        [[NSUserDefaults standardUserDefaults] setObject:device forKey:@"DeviceToken"];
        [[NSUserDefaults standardUserDefaults] synchronize];

        NSLog(@"My device is: %@", device);
    }

    - (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
    {
        NSLog(@"Failed to get token, error: %@", error);
    }

    -(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userPushInfo
    {

        application.applicationIconBadgeNumber = 0;
        NSDictionary *fetchedDictionary =[userPushInfo objectForKey:@"aps"];
        NSDictionary *fetchedDictionaryalert = [fetchedDictionary objectForKey:@"alert"];
        NSDictionary *fetchedDictionarybody = [fetchedDictionaryalert objectForKey:@"body"];
        NSDictionary *fetchedDictionaryactivation = [fetchedDictionarybody objectForKey:@"activation_code"];

        if(fetchedDictionaryactivation != nil)
        {
            NSDictionary *fetchedDictionaryresult = [fetchedDictionaryactivation objectForKey:@"result"];
            for (NSDictionary *user in fetchedDictionaryresult)
            {
                responseActCode = [user objectForKey:@"activation_code"];
                responseParentID = [user objectForKey:@"parent_id"];
                NSLog(@"Item actcode: %@", responseActCode);
                NSLog(@"Item parentid: %@", responseParentID);
            }
            UIAlertView *alertView = [[UIAlertView alloc]
                                      initWithTitle:@"Activation Code"
                                      message:(@"%@", responseActCode)
                                      delegate:self
                                      cancelButtonTitle: @"Ok"
                                      otherButtonTitles: nil];
            [alertView show];
            alertView.tag = 0;
            NSLog(@"dadadad %@", userPushInfo);

        }
        else
        {
            NSDictionary *fetchedDictionary =[userPushInfo objectForKey:@"aps"];
            NSDictionary *fetchedDictionaryalert = [fetchedDictionary objectForKey:@"alert"];
            NSDictionary *fetchedDictionarybody = [fetchedDictionaryalert objectForKey:@"body"];
            NSDictionary *fetchedDictionaryresult = [fetchedDictionarybody objectForKey:@"result"];
            //NSString *beaconID;
            for (NSDictionary *user in fetchedDictionaryresult)
            {
                beaconID = [user objectForKey:@"beacon_id"];
                mess = [user objectForKey:@"message"];
                NSLog(@"Item actcode: %@", beaconID);
                NSLog(@"Item parentid: %@", mess);
            }

            UIAlertView *alertView = [[UIAlertView alloc]
                                      initWithTitle:@""
                                      message:(@"%@", mess)
                                      delegate:self
                                      cancelButtonTitle: @"Ok"
                                      otherButtonTitles: nil];
            [alertView show];
            alertView.tag = 1;
            NSLog(@"dadadad %@", userPushInfo);

        }

    }


    -(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger) buttonIndex
    {
        if (alertView.tag==0)
        {
            NSString *parentiD = responseParentID;
            NSString *actcode = responseActCode;
            NSString *beaconid = @"1458010000B0";

            NSMutableURLRequest *request = nil;
            NSString *getURL = [NSString stringWithFormat:@"%@?parent_id=%@&beacon_id=%@&activation_code=%@", URL2, parentiD, beaconid, actcode];
            getURL = [getURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSURL *url =  [NSURL URLWithString: getURL];
            request = [NSMutableURLRequest requestWithURL:url];

            NSLog(@"link: %@", getURL);

            [request setHTTPMethod:@"GET"];
            [request addValue: @"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

            NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

            NSLog(@"connection: %@", connection);

            if( connection )
            {
                mutData = [NSMutableData new];
            }
            else
            {
                NSLog (@"NO_CONNECTION");
                return;
            }
        }
        else if(alertView.tag == 1)
        {

            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            ChildListViewController *childcheck = (ChildListViewController *)[storyboard instantiateViewControllerWithIdentifier:@"ChildStoryBoard"];
            NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
            childcheck.childNameData =[_childNameData objectAtIndex:indexPath.row];
            self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
            [self.window setRootViewController:childcheck];
            [self.window makeKeyAndVisible];


            NSLog (@"Move to next View controller");
        }
    }

     #pragma mark NSURLConnection delegates

     -(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response
     {
     [mutData setLength:0];
     }

     -(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
     {
     [mutData appendData:data];
     }

     -(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
     {

     return;
     }

     -(void)connectionDidFinishLoading:(NSURLConnection *)connection
     {
         /*NSString *responseStringWithEncoded = [[NSString alloc] initWithData: mutData encoding:NSUTF8StringEncoding];
         NSLog(@"Response from Server : %@", responseStringWithEncoded);
        */
         NSError *error = nil;
         NSDictionary *json = [NSJSONSerialization JSONObjectWithData:mutData options:kNilOptions error:&error];
         NSArray *fetchedArr = [json objectForKey:@"child_info"];

         for (NSDictionary *user in fetchedArr)
         {
             beaconID = [user objectForKey:@"beacon_id"];
             Name = [user objectForKey:@"name"];
             trackerID = [user objectForKey:@"tracker_id"];
             lat = [user objectForKey:@"latitude"];
             longi = [user objectForKey:@"longitude"];
             Status = [user objectForKey:@"status"];
             Image = [user objectForKey:@"image"];

             NSLog(@"Item beacID: %@", beaconID);
             NSLog(@"Item nam: %@", Name);
             NSLog(@"Item trackID: %@", trackerID);
             NSLog(@"Item lati: %@", lat);
             NSLog(@"Item longi: %@", longi);
             NSLog(@"Item stat: %@", Status);
             NSLog(@"Item ima: %@", Image);

             //NSLog(@"Item parentid: %@", [user objectForKey:@"parent_id"]);
             //NSLog(@"Item actcode: %@", [user objectForKey:@"activation_code"]);
         }



     //NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
     //[defaults setObject:responseActCode forKey:@"HighScore"];
     //[defaults synchronize];
     //NSLog(@"from data: %@", [defaults objectForKey:@"HighScore"]);
     }




    - (void)applicationWillResignActive:(UIApplication *)application {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    - (void)applicationDidEnterBackground:(UIApplication *)application {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    - (void)applicationWillEnterForeground:(UIApplication *)application {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }

    - (void)applicationDidBecomeActive:(UIApplication *)application {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        //Name = [[NSString alloc]init];
    }

    - (void)applicationWillTerminate:(UIApplication *)application {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

@end

AppDelegate.h



  #import <UIKit/UIKit.h>
    #import "ChildListViewController.h"



    @interface AppDelegate : UIResponder <UIApplicationDelegate>
    {
        NSMutableData *mutData;
        NSString *responseActCode;
        NSString *responseParentID;
        NSString *mess;

        NSString *beaconID;
        NSString *Name;
        NSString *Status;
        NSString *Image;

        NSString *trackerID;
        NSString *lat;
        NSString *longi;

    }

    @property (strong, nonatomic) UIWindow *window;
    @property (strong, nonatomic) NSString *responseActCode;
    @property (strong, nonatomic) NSString *responseParentID;
    @property (strong, nonatomic) NSString *mess;


    @property (readonly) NSString *beaconID;
    @property (readonly) NSString *Name;
    @property (readonly) NSString *trackerID;
    @property (readonly) NSString *lat;
    @property (readonly) NSString *longi;
    @property (readonly) NSString *Status;
    @property (readonly) NSString *Image;

3 Answers3

0

U can try this, i'm not sure if it work but hope it help

In AppDelegate.h: Add property to that stuff u want to pass, eg. @property (strong, nonatomic) NSString *string;

In AppDelegate.m: Assign value to it

In YourVC.m:

#import "AppDelegate.h"

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *yourString = [appDelegate string];
Tj3n
  • 9,837
  • 2
  • 24
  • 35
0

You have your data in Appdelegate now. Just create an object of it in file(Table view for you) where you need data and you can access your data now anywhere you want in that project.

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

NSlog(@"appDelegate.fechedArray==%@",appDelegate.fechedArray);
Shirish
  • 295
  • 3
  • 19
0

in AppDelegate.h

#define XAppDelegate ((AppDelegate *)[[UIApplication sharedApplication] delegate])

@interface AppDelegate : UIResponder <UIApplicationDelegate>


@end

and now you can access to your AppDelegate everywhere like this :

XAppDelegate.something
poyo fever.
  • 742
  • 1
  • 5
  • 22