ios如何将refreshToken从appdelegate发送到viewcontroller

时间:2017-03-24 11:21:45

标签: ios objective-c viewcontroller appdelegate

我是开发IOS应用程序的初学者。现在我想从AppDelegate中的方法向mainViewController发送一个refreshToken数据。 我第一次下载时无法得到它。但第二次我能得到它。 我认为它第一次创建需要一些时间,然后存储。 请帮助我,如何将方法中的数据从AppDelegate发送到ViewController。最终,我想将它存储到数据库并从服务器端向用户发送推送通知消息。 我使用以下代码。

// AppDelegate.h

@class ViewController;
#import <UIKit/UIKit.h>
#import "ViewController.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (weak, nonatomic) ViewController *myViewController;
@property (strong, nonatomic) UIWindow *window;
@property (weak, nonatomic) IBOutlet UIWebView *webView;     
@end

// AppDelegate.m

- (void)tokenRefreshCallback: (NSNotification *)notification {
NSString *refreshToken = [[FIRInstanceID instanceID] token];
NSLog(@"InstanceID token: %@", refreshToken);

//
if(refreshToken){
    [[NSUserDefaults standardUserDefaults] setObject:refreshToken forKey:@"token"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
// Connect to FCM since connection may have failed when attempted before having a token.

[self connectToFirebase];

}

// ViewController.h

#import <UIKit/UIKit.h>
#import "AppDelegate.h"
@interface ViewController : UIViewController

@end

// ViewController.m

- (void)viewDidLoad {
[super viewDidLoad];

AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
appDelegate.myViewController = self;

//get tokenId
NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
if(token){
    NSLog(@"i have token~!!!: %@ ", token);
}else NSLog(@"no token!: %@ ", token);
// Do any additional setup after loading the view, typically from a nib.    

}

谢谢大家。

1 个答案:

答案 0 :(得分:0)

使用NSNotifiactionCenter

在您的Appdelegate中,当令牌在带有令牌的通知后可用时(在令牌可用的app delegate中添加以下代码)

 NSDictionary* userInfo = @{@"token": @"YOUR_TOKEN"};

[[NSNotificationCenter defaultCenter] postNotificationName:@"refreshTokenAvailale" object:self userInfo:userInfo];

并将此代码放入主视图控制器

- (void) dealloc
{
// If you don't remove yourself as an observer, the Notification   Center
// will continue to try and send notification objects to the deallocated
// object.
    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

- (id) init
{

    [[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(receiveNotification:) 
    name:@"refreshTokenAvailale"
    object:nil];

    return self;
}

- (void) receiveNotification:(NSNotification *) notification
{

    if ([notification.name isEqualToString:@"refreshTokenAvailale"])
    {
        NSDictionary* userInfo = notification.userInfo;
        NSString* token = userInfo[@"token"];
    }

 }