[iphone] 포 그라운드 iOS의 앱에서 푸시 알림 받기

내 앱에서 푸시 알림 서비스를 사용하고 있습니다. 앱이 백그라운드에있을 때 알림 화면 (iOS 기기 상단에서 아래로 스 와이프하면 화면이 표시됨)에서 알림을 볼 수 있습니다. 그러나 응용 프로그램이 포 그라운드에 있으면 델리게이트 메소드

- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo

메시지가 표시되지만 알림 화면에 알림이 표시되지 않습니다.

앱이 백그라운드인지 전경인지에 관계없이 알림 화면에 알림을 표시하고 싶습니다. 해결책을 찾아 피곤하다. 도움을 주시면 감사하겠습니다.



답변

앱이 포 그라운드에있는 동안 배너 메시지를 표시하려면 다음 방법을 사용하십시오.

iOS 10, Swift 3/4 :

// This method will be called when app received push notifications in foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) 
{
    completionHandler([.alert, .badge, .sound])
}

iOS 10, Swift 2.3 :

@available(iOS 10.0, *)
func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void)
{
    //Handle the notification
    completionHandler(
       [UNNotificationPresentationOptions.Alert,
        UNNotificationPresentationOptions.Sound,
        UNNotificationPresentationOptions.Badge])
}

또한 알림 센터의 대리인으로 앱 대리인을 등록해야합니다.

import UserNotifications

// snip!

class AppDelegate : UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate

// snip!

   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

      // set the delegate in didFinishLaunchingWithOptions
      UNUserNotificationCenter.current().delegate = self
      ...
   }


답변

아래 코드가 도움이 될 것입니다.

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo  {
    application.applicationIconBadgeNumber = 0;             
    //self.textView.text = [userInfo description];
    // We can determine whether an application is launched as a result of the user tapping the action
    // button or whether the notification was delivered to the already-running application by examining
    // the application state.

    if (application.applicationState == UIApplicationStateActive) {                
        // Nothing to do if applicationState is Inactive, the iOS already displayed an alert view.                
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Did receive a Remote Notification" message:[NSString stringWithFormat:@"Your App name received this notification while it was running:\n%@",[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]]delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView show];          
    }    
}


답변

누구나 관심을 가질 수 있도록 상단의 시스템 푸시 배너처럼 보이는 사용자 정의보기를 만들었지 만 닫기 버튼 (작은 파란색 X)과 사용자 정의 작업을 위해 메시지를 탭하는 옵션을 추가했습니다. 또한 사용자가 이전 알림을 읽거나 닫을 시간이되기 전에 도착한 둘 이상의 알림의 경우를 지원합니다 (얼마나 많은 사람이 쌓일 수 있는지에 대한 제한은 없습니다 …)

GitHub에 링크 : AGPushNote

사용법은 기본적으로 라이너입니다.

[AGPushNoteView showWithNotificationMessage:@"John Doe sent you a message!"];

그리고 iOS7에서 이와 같이 보입니다 (iOS6에는 iOS6 모양과 느낌이 있습니다 …)

여기에 이미지 설명을 입력하십시오


답변

목표 C

여기에 이미지 설명을 입력하십시오

에 알림 배너 표시를위한 iOS 10통합 willPresentNotification방법이 필요합니다 foreground.

앱이 포 그라운드 모드 인 경우 (활성)

- (void)userNotificationCenter:(UNUserNotificationCenter* )center willPresentNotification:(UNNotification* )notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
    NSLog( @“Here handle push notification in foreground" );
    //For notification Banner - when app in foreground

    completionHandler(UNNotificationPresentationOptionAlert);

    // Print Notification info
    NSLog(@"Userinfo %@",notification.request.content.userInfo);
}


답변

애플리케이션이 포 그라운드에서 실행중인 경우 iOS는 알림 배너 / 경고를 표시하지 않습니다. 의도적으로 설계된 것입니다. 그러나 우리는 UILocalNotification다음과 같이 사용하여 그것을 달성 할 수 있습니다

  • 원격
    알림 을 수신 할 때 응용 프로그램이 활성 상태인지 확인하십시오 . 활성 상태 인 경우 UILocalNotification을 실행하십시오.

    if (application.applicationState == UIApplicationStateActive ) {
    
        UILocalNotification *localNotification = [[UILocalNotification alloc] init];
        localNotification.userInfo = userInfo;
        localNotification.soundName = UILocalNotificationDefaultSoundName;
        localNotification.alertBody = message;
        localNotification.fireDate = [NSDate date];
        [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
    }

빠른:

if application.applicationState == .active {
    var localNotification = UILocalNotification()
    localNotification.userInfo = userInfo
    localNotification.soundName = UILocalNotificationDefaultSoundName
    localNotification.alertBody = message
    localNotification.fireDate = Date()
    UIApplication.shared.scheduleLocalNotification(localNotification)
}


답변

애플리케이션이 포 그라운드에서 실행중인 경우 iOS는 알림 배너 / 경고를 표시하지 않습니다. 의도적으로 설계된 것입니다. 앱이 포 그라운드에있는 동안 알림을받는 상황을 처리하려면 코드를 작성해야합니다. 가장 적절한 방법으로 알림을 표시해야합니다 (예 : UITabBar아이콘에 배지 번호 추가 , 알림 센터 배너 시뮬레이션 등).


답변

Xcode 10 스위프트 4.2

앱이 포 그라운드에있을 때 푸시 알림을 표시하려면-

1 단계 : AppDelegate 클래스에 델리게이트 UNUserNotificationCenterDelegate를 추가합니다.

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

2 단계 : UNUserNotificationCenter 대리인 설정

let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.delegate = self

3 단계 : 이 단계에서는 앱이 포 그라운드에있는 경우에도 앱에서 푸시 알림을 표시 할 수 있습니다.

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .sound])

    }

4 단계 : 이 단계는 선택 사항 입니다. 앱이 포 그라운드에 있는지 확인하고 포 그라운드에 있으면 로컬 PushNotification을 표시하십시오.

func application(_ application: UIApplication,didReceiveRemoteNotification userInfo: [AnyHashable: Any],fetchCompletionHandler completionHandler:@escaping (UIBackgroundFetchResult) -> Void) {

        let state : UIApplicationState = application.applicationState
        if (state == .inactive || state == .background) {
            // go to screen relevant to Notification content
            print("background")
        } else {
            // App is in UIApplicationStateActive (running in foreground)
            print("foreground")
            showLocalNotification()
        }
    }

지역 알림 기능-

fileprivate func showLocalNotification() {

        //creating the notification content
        let content = UNMutableNotificationContent()

        //adding title, subtitle, body and badge
        content.title = "App Update"
        //content.subtitle = "local notification"
        content.body = "New version of app update is available."
        //content.badge = 1
        content.sound = UNNotificationSound.default()

        //getting the notification trigger
        //it will be called after 5 seconds
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)

        //getting the notification request
        let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)

        //adding the notification to notification center
        notificationCenter.add(request, withCompletionHandler: nil)
    }