4

UILocalNotification의 사용 방법에 대한 가이드를 읽었습니다. 그래서 시도해 보았고 첫 시도부터 성공하지 못했습니다. 응용 프로그램은를 실행 중일 때로컬 알림은 장치에서 작동하지 않지만 시뮬레이터에서 작동합니다

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
    { 
    ... 
    //if it is iOS 8 
    if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) 
    { 
     UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotificationTypeSound) categories:nil]; 
     [application registerUserNotificationSettings:settings]; 
    } 
    else // if iOS 7 
    { 
     UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound; 
     [application registerForRemoteNotificationTypes:myTypes]; 
    } 

    UILocalNotification *locationNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]; 
    if (locationNotification) { 
     // Set icon badge number to zero 
     application.applicationIconBadgeNumber = 0; 
     } 

     return YES; 
    } 

및 알림을받을 수 :

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification 
    { 
    NSLog(@"notification recieved %@",notification.alertBody); 
    // NSLog(@"notification userinfo %@",notification.userInfo); 
    UIApplicationState state = [application applicationState]; 
    if (state == UIApplicationStateActive) { 
     NSLog(@"notification fired in foreground"); 
     UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Notification!" 
                 message:notification.alertBody 
                delegate:nil 
              cancelButtonTitle:@"OK" 
              otherButtonTitles:nil]; 

    [message show]; 
    } else if (state == UIApplicationStateInactive){ 
     NSLog(@"notification fired in inactive"); 

    } else if (state == UIApplicationStateBackground){ 
     NSLog(@"notification fired in background"); 
     } 


    } 

을 그리고 모든 시뮬레이터에 너무 장치에 괜찮 - 응용 프로그램 인 경우 AppDelegate.m에 알림을 등록하려면 내가 사용 나는 예약 된 알림을받습니다. 그러나 응용 프로그램이 비활성 상태 일 때 응용 프로그램, 즉 실행되지 않을 때 알림을받을 필요가

문제는 내가 예를 들어 버튼을 눌러 내 알림을 shedule 경우, 내가 어떤없이 그것을 얻을 것이다 (집은 한 번 누름) 문제는 알림 센터에 표시되며 내 앱 아이콘에 배지가 추가됩니다. 하지만 내 AFNetworking 작업이 종료 될 때만 알림을 수신하려고합니다. 알림을 설정하려면 내가 방법에 따라 사용하십시오

:

-(void)getProgress{ 
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; 
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
    NSString *token = [defaults objectForKey:@"token"]; 
    NSString *header = [NSString stringWithFormat:@"Bearer %@",token]; 
    NSDictionary *params = @{@"lang": @"en",@"project":projId}; 
    manager.responseSerializer = [AFJSONResponseSerializer serializer]; 
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"Authorization"]; 
    [manager POST:@"http://example.com/api/get-progress" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { 
     if ([[responseObject objectForKey:@"result"]isEqualToString:@"success"]){ 
      progCreate = [responseObject objectForKey:@"progress"]; 
      if ([progCreate intValue]==100){ 
       //shedule notification for immediately showing 
       UILocalNotification* localNotification = [[UILocalNotification alloc] init]; 
       localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:0]; 
       localNotification.alertBody = [NSString stringWithFormat:@"Notification text!"]; 
       localNotification.alertAction = @"Show"; 
       localNotification.timeZone = [NSTimeZone defaultTimeZone]; 
       localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1; 
       [localNotification setSoundName:UILocalNotificationDefaultSoundName]; 
       [[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; 
      // [[UIApplication sharedApplication]presentLocalNotificationNow:localNotification]; the same result as above 
      } 

     } 

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
     [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; 
     NSLog(@"Error: %@", error); 
     }]; 
    } 

가장 큰 문제에만 iOS 버전과 시뮬레이터에서 작동 이 방법은 8.0하고 아이폰 OS 7.1.1와 아이폰 4에서 작동하지 않는다는 것입니다 iPhone 5c와 iOS 8.1.2는 iOS 7.1과 함께 시뮬레이터에서 작동하지 않습니다. iOS 7.1 이상의 실제 기기 및 시뮬레이터에서 백그라운드에서 알림을 수신하는 것으로 눈치 채지 못했지만 앱을 열면 알림을받을 수 있습니다 (AppDelegate.m으로 설정 됨). 기꺼이 기다려주세요. 모든 제안 및 도움.

+0

왜 화재 날짜가 즉시 설정되어 있습니까? 포 그라운드에서 항상 당신을 위해 불을 피우지 않겠습니까? 그것은 나의 상태를 만족시키기 때문에 미래 날짜 –

+0

@ 스텐 브 리치에서 발사해야합니다. 'progCreate == 100' – vendettacore

+0

@Bhavin 아니요, 서버 쪽에서 푸시 알림으로 해결했지만 로컬 알림에 여전히 – vendettacore

답변

3

iOS 8.0 이상의 시뮬레이터에서 알림을받는 사실은 iOS 시뮬레이터 런타임의 제한 사항입니다. 기기에서 앱이 백그라운드에서 실행 중이지만 실제로 실행되지 않으면 작업이 일시 중지됩니다. iOS 시뮬레이터에서 작업은 백그라운드에서 계속 실행됩니다.

+0

어떤 작업에 대해 이야기하고 있습니까? 내'getProgress' 작업이 백그라운드에서 작동하지 않는다는 것을 의미한다면 그것은 틀린 것입니다.왜냐하면 애플 리케이션이 실행 중이 아니고 다시 열리는 과정이 변경 되었기 때문에 나는 왜 태스크가 작동하면 알림이 백그라운드에서 전송되지 않는지 이해할 수 없다. – vendettacore

+0

실행 중일 때, 앱은 mach task/BSD 프로세스이다. 사용자가 백그라운드에서 앱을 배치하면 작업이 일시 중지됩니다 (CPU에 시간이 없습니다). 시뮬레이션에서는 백그라운드에 배치 될 때 작업이 계속 실행됩니다. 이것은 시뮬레이터 런타임의 버그로 장치와 일치하지 않습니다. –

+0

예, UILocalNotification을 사용하여 샘플 알림을 게시하려고했습니다. iOS Simulator "iPhone 6/8.3"에서 작동하지 않습니다. –

0

때로는 현지 알림을받지 못하지만 1 시간 후에 거의 알림을받습니다. 그래서 특정 시간을 기다렸다가 다시 확인하십시오.

+0

제 경우에는 즉석 알림을 받아야합니다. 예를 들어 – vendettacore

+0

과 같이 다운로드 완료에 대한 알림이 표시되지 않기 때문에 알림을 설정하는 시간과 날짜를 확인하십시오. –

5

Objective-C를 사용하고 있습니다. 이 질문을 1 년 전에 물어 보았을 때, 아마도 이것을 알아 냈거나 스위프트 2.0을 사용하고있을 것입니다. 나는 같은 문제가 있었고 다음 코드를 추가하여 Swift 2.0으로 해결할 수있었습니다.

AppDelegate.swift :

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 
    // Override point for customization after application launch. 

    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)) 
    application.beginBackgroundTaskWithName("showNotification", expirationHandler: nil) 

    return true 
} 

당신은 내 전체 대답 here을 볼 수 있습니다.

관련 문제