将AppDelegate中的数据传递给Table View单元格

时间:2015-12-04 10:39:52

标签: ios pass-data

我需要一些帮助才能将数据从AppDelegate传递到另一个控制台,这是一个Table View Controller。在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;

3 个答案:

答案 0 :(得分:0)

你可以试试这个,我不确定它是否有用但希望能有所帮助

AppDelegate.h中:为你想传递的东西添加属性,例如。 @property (strong, nonatomic) NSString *string;

AppDelegate.m中:为其指定值

YourVC.m

#import "AppDelegate.h"

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

答案 1 :(得分:0)

您现在在Appdelegate中拥有数据。只需在文件中创建一个对象(适合您的表视图),您需要数据,并且您现在可以在该项目中的任何位置访问您的数据。

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

NSlog(@"appDelegate.fechedArray==%@",appDelegate.fechedArray);

答案 2 :(得分:0)

在AppDelegate.h中

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

@interface AppDelegate : UIResponder <UIApplicationDelegate>


@end

现在你可以像这样访问你的AppDelegate:

XAppDelegate.something