투케이2K

58. (Objective-C/objc) [간단 소스] AppDelegate 앱 딜리게이트 파이어베이스 푸시 (firebase push) 적용 실시 본문

Objective-C

58. (Objective-C/objc) [간단 소스] AppDelegate 앱 딜리게이트 파이어베이스 푸시 (firebase push) 적용 실시

투케이2K 2022. 9. 5. 18:01
반응형

[개발 환경 설정]

개발 툴 : XCODE

개발 언어 : OBJECTIVE-C

 

 

 

[delegate.h : 소스 코드]

// MARK: [KWON] : [푸시 알림 작업]
#import <Firebase/Firebase.h>
#import <UserNotifications/UserNotifications.h>


@interface AppDelegate : UIResponder <UIApplicationDelegate, UNUserNotificationCenterDelegate>
{
}


@end

 [delegate.m : 소스 코드]

#import "HelloWorldAppDelegate.h"

// MARK: [KWON] : [푸시 알림 작업]
#import <Firebase/Firebase.h>
#import <UserNotifications/UserNotifications.h>





@interface AppDelegate()
@end





- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    printf("\n");
    printf("==================================== \n");
    printf("[HelloWorldAppDelegate >> didFinishLaunchingWithOptions() :: 앱 초기 실행 실시] \n");
    printf("==================================== \n");
    printf("\n");
    
    // ---------------------------------------
    
    // MARK: [KWON] : [푸시 알림 작업] : [알림 팝업창 권한 요청 실시]
    UIUserNotificationType allNotificationTypes =
    (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
    UIUserNotificationSettings *settings =
    [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    
    // ---------------------------------------
    
    // MARK: [KWON] : [푸시 알림 작업] : [파이어베이스 configure 초기화 실시]
    [FIRApp configure];
    
    // ---------------------------------------
    
    // MARK: [KWON] : [푸시 알림 작업] : [푸시 토큰 확인 메소드 등록]
    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(onTokenRefresh)
     name:kFIRInstanceIDTokenRefreshNotification object:nil];
    
    
    NSString *refreshedToken = [[FIRInstanceID instanceID] token];
    [[NSUserDefaults standardUserDefaults] setObject:refreshedToken forKey:[S_FinalData PRE_PUSH_TOKEN]];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    printf("\n");
    printf("==================================== \n");
    printf("[HelloWorldAppDelegate >> didFinishLaunchingWithOptions() :: 파이어베이스 저장 된 푸시 토큰 확인 실시] \n");
    printf("[token :: %s] \n", refreshedToken.description.UTF8String);
    printf("==================================== \n");
    printf("\n");

    // ---------------------------------------
    // MARK: [포그라운드 푸시 상태 바 추가 알림 표시 >> userNotificationCenter : willPresentNotification 에서 처리]
    [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
    // ---------------------------------------
    
    // ---------------------------------------
    return YES;
    // ---------------------------------------
}





// MARK: [KWON] : [푸시 알림 작업] : [푸시 토큰 갱신 확인]
- (void)onTokenRefresh {
    NSString *refreshedToken = [[FIRInstanceID instanceID] token];
    printf("\n");
    printf("==================================== \n");
    printf("[HelloWorldAppDelegate >> onTokenRefresh() :: 파이어베이스 갱신 된 푸시 토큰 확인 실시] \n");
    printf("[token :: %s] \n", refreshedToken.description.UTF8String);
    printf("==================================== \n");
    printf("\n");
    
    // [프리퍼런스에 데이터 저장 실시]
    [[NSUserDefaults standardUserDefaults] setObject:refreshedToken forKey:[S_FinalData PRE_PUSH_TOKEN]];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    // [파이어베이스 연결 상태 체크 실시]
    [self connectToFcm];
    
    // TODO: If necessary send token to application server.
    //[self sendRegistrationToServer:refreshedToken];
}






// MARK: [KWON] : [푸시 알림 작업] : [파이어베이스 연결 상태 확인]
- (void)connectToFcm {
    [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
        if (error != nil) {
            printf("\n");
            printf("==================================== \n");
            printf("[HelloWorldAppDelegate >> connectToFcm() :: 파이어베이스 연결 에러] \n");
            printf("[error :: %s] \n", error.description.UTF8String);
            printf("==================================== \n");
            printf("\n");
        } else {
            printf("\n");
            printf("==================================== \n");
            printf("[HelloWorldAppDelegate >> connectToFcm() :: 파이어베이스 연결 성공] \n");
            printf("==================================== \n");
            printf("\n");
        }
    }];
}






// MARK: [KWON] : [푸시 알림 작업] : [파이어베이스 푸시 메시지 수신 확인]
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
    if (notificationSettings.types != UIUserNotificationTypeNone) {
        printf("\n");
        printf("==================================== \n");
        printf("[HelloWorldAppDelegate >> didRegisterUserNotificationSettings() :: 파이어베이스 리모트 알림 등록 요청] \n");
        printf("==================================== \n");
        printf("\n");
        
        [application registerForRemoteNotifications];
    } else {
        printf("\n");
        printf("==================================== \n");
        printf("[HelloWorldAppDelegate >> didRegisterUserNotificationSettings() :: 파이어베이스 리모트 알림 등록 상태] \n");
        printf("==================================== \n");
        printf("\n");
    }
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"Registration for remote notification failed with error: %@", error.localizedDescription);
    printf("\n");
    printf("==================================== \n");
    printf("[HelloWorldAppDelegate >> didFailToRegisterForRemoteNotificationsWithError() :: 파이어베이스 푸시 메시지 수신 에러] \n");
    printf("[error :: %s] \n", error.localizedDescription.UTF8String);
    printf("==================================== \n");
    printf("\n");
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void(^)(UIBackgroundFetchResult))completionHandler {
    NSString *appLifeCycle = [[S_Preference shared] getStringWith_sKey:[S_FinalData PRE_ROOT_ACTIVITY]];
    printf("\n");
    printf("==================================== \n");
    printf("[HelloWorldAppDelegate >> didReceiveRemoteNotification() :: 파이어베이스 푸시 메시지 수신 확인] \n");
    printf("[userInfo :: %s] \n", userInfo.description.UTF8String);
    printf("[appLifeCycle :: %s] \n", appLifeCycle.description.UTF8String);
    printf("==================================== \n");
    printf("\n");
    
    if ([[C_Util shared] stringNotNullWithStr:appLifeCycle] == true) { // [앱 라이프 사이클이 널이 아닌 경우 : 포그라운드]
        
        /*
        // [푸시 메시지 알림 팝업창 표시]
        NSDictionary *push_aps = [userInfo objectForKey:@"aps"];
        
        if ([[push_aps objectForKey:@"alert"] isKindOfClass:[NSDictionary class]]) {
            
            NSDictionary *push_alert = [push_aps objectForKey:@"alert"];
           
            NSString *push_title = [push_alert objectForKey:@"title"];
            NSString *push_body = [push_alert objectForKey:@"body"];
            
            
            UIAlertView *alert_push = [[UIAlertView alloc]initWithTitle:push_title message:push_body delegate:self cancelButtonTitle:@"확인" otherButtonTitles:nil, nil];
            [alert_push show];
        }
        // */ 
    }
    else { // [널인 경우 백그라운드]

        // [푸시 알림 뱃지 표시]
        [UIApplication sharedApplication].applicationIconBadgeNumber = 1;
    }
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler  API_AVAILABLE(ios(10.0)) {
    NSString *push_title = notification.request.content.title;
    NSString *push_body = notification.request.content.body;
    printf("\n");
    printf("==================================== \n");
    printf("[HelloWorldAppDelegate >> willPresentNotification() :: [포그라운드] 푸시 노티피케이션 알림 확인] \n");
    printf("[title :: %s] \n", push_title.description.UTF8String);
    printf("[body :: %s] \n", push_body.description.UTF8String);
    printf("==================================== \n");
    printf("\n");
    
    // MARK: [포그라운드 푸시 알림 팝업창 표시]
    NSString *appLifeCycle = [[S_Preference shared] getStringWith_sKey:[S_FinalData PRE_ROOT_ACTIVITY]];
    if ([[C_Util shared] stringNotNullWithStr:appLifeCycle] == true) { // [앱 라이프 사이클이 널이 아닌 경우 : 포그라운드]
    
        UIAlertView *alert_push = [[UIAlertView alloc]initWithTitle:push_title message:push_body delegate:self cancelButtonTitle:@"확인" otherButtonTitles:nil, nil];
        [alert_push show];
        
    }
    
    // MARK: [포그라운드 푸시 알림 배너 표시]
    completionHandler(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
}





// MARK: [KWON] : [푸시 알림 작업] : [앱 딜리게이트 라이프사이클 정의]
- (void)applicationDidBecomeActive:(UIApplication *)application {
    printf("\n");
    printf("==================================== \n");
    printf("[HelloWorldAppDelegate >> applicationDidBecomeActive() :: 앱 사용자 응답 준비 확인 실시] \n");
    printf("==================================== \n");
    printf("\n");
    
    // [프리퍼런스에 데이터 저장 실시]
    [[S_Preference shared] setStringWith_sKey:[S_FinalData PRE_ROOT_ACTIVITY] _sValue:@"TRUE"];
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
    printf("\n");
    printf("==================================== \n");
    printf("[HelloWorldAppDelegate >> applicationWillEnterForeground() :: 앱 포그라운드 상태 확인 실시] \n");
    printf("==================================== \n");
    printf("\n");
}
- (void)applicationWillResignActive:(UIApplication *)application {
    printf("\n");
    printf("==================================== \n");
    printf("[HelloWorldAppDelegate >> applicationWillResignActive() :: 앱 사용자 응답 중지 상태 확인 실시] \n");
    printf("==================================== \n");
    printf("\n");
    
    // [프리퍼런스에 데이터 저장 실시]
    [[S_Preference shared] setStringWith_sKey:[S_FinalData PRE_ROOT_ACTIVITY] _sValue:@""];
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
    printf("\n");
    printf("==================================== \n");
    printf("[HelloWorldAppDelegate >> applicationDidEnterBackground() :: 앱 백그라운드 상태 확인 실시] \n");
    printf("==================================== \n");
    printf("\n");
    
    // [푸시 알림 뱃지 0으로 변경]
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}
- (void)applicationWillTerminate:(UIApplication *)application {
    printf("\n");
    printf("==================================== \n");
    printf("[HelloWorldAppDelegate >> applicationWillTerminate() :: 앱 작업 목록 날림 감지 확인] \n");
    printf("==================================== \n");
    printf("\n");
    
    // [프리퍼런스에 데이터 저장 실시]
    [[S_Preference shared] setStringWith_sKey:[S_FinalData PRE_ROOT_ACTIVITY] _sValue:@""];
}

 

반응형
Comments