Передайте данные в AppDelegate в ячейку Table View

Мне нужна помощь в передаче данных из AppDelegate в другой контроллер, который является контроллером табличного представления. В AppDelegate у меня есть ответ сервера, который я преобразовал в строку. Я хочу передать эту строку другому контроллеру (контроллеру табличного представления) и отобразить ее в ячейке.

Это мой код в 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;

person Community    schedule 04.12.2015    source источник
comment
вы можете сохранить эту строку в NSUserDefaults, а затем использовать ее в любом месте приложения.   -  person Divyanshu Sharma    schedule 04.12.2015
comment
но как я могу применить это к моему приложению, сэр?   -  person    schedule 04.12.2015


Ответы (3)


Вы можете попробовать это, я не уверен, что это сработает, но надеюсь, что это поможет

В AppDelegate.h: добавьте свойство к тому материалу, который вы хотите передать, например. @property (strong, nonatomic) NSString *string;

В AppDelegate.m: присвойте ему значение

In YourVC.m:

#import "AppDelegate.h"

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *yourString = [appDelegate string];
person Tj3n    schedule 04.12.2015

Теперь у вас есть данные в Appdelegate. Просто создайте его объект в файле (представление таблицы для вас), где вам нужны данные, и вы можете получить доступ к своим данным сейчас в любом месте этого проекта.

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

NSlog(@"appDelegate.fechedArray==%@",appDelegate.fechedArray);
person Shirish    schedule 04.12.2015

в AppDelegate.h

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

@interface AppDelegate : UIResponder <UIApplicationDelegate>


@end

и теперь вы можете получить доступ к своему AppDelegate везде, например:

XAppDelegate.something
person poyo fever.    schedule 04.12.2015