簡體   English   中英

iOS如何從appdelegate發送refreshToken到viewcontroller

[英]ios how to send refreshToken from appdelegate to viewcontroller

我是開發IOS應用程序的初學者。 現在,我想從AppDelegate中的方法向主視圖控制器發送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.    

}

謝謝大家

使用NSNotifiactionCenter

當令牌可用時,在您的Appdelegate中發布帶有令牌的通知(在令牌可用的應用委托中添加以下代碼)

 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"];
    }

 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM