ios - 本地通知不适用于设备,但适用于模拟器

标签 ios objective-c background ios-simulator uilocalnotification

我已经阅读了一些关于如何使用 UILocalNotification 的指南。因此,自从我第一次尝试以来,我已经尝试过但没有成功。要在 AppDelegate.m 中注册通知,我使用:

    - (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");
         }


    }

模拟器和设备上的一切都正常 - 当应用程序运行时,我收到预定的通知。但是我需要在应用程序未运行时接收通知,即当应用程序处于非事件状态时(按一次主页)

问题是,例如,如果我在按下按钮时安排我的通知,我会毫无问题地收到它,它会显示在通知中心,并且角标(Badge)会根据需要添加到我的应用程序图标上。但我只想在我的 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 版本的模拟器,不适用于装有 iOS 7.1.1 的 iPhone 4 和装有 iOS 8.1.2 的 iPhone 5c 它也不起作用在 iOS 7.1 的模拟器上工作。 在使用 iOS 7.1+ 的真实设备和模拟器上,我从来没有注意到在后台收到通知,只有在我打开应用程序时才能收到通知(然后它会显示我在 AppDelegate.m 中设置的警报>) 我很乐意提供任何建议和帮助。

最佳答案

我看到您正在使用 Objective-C。考虑到这个问题是一年前提出的,您可能已经解决了这个问题,或者您现在正在使用 Swift 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 .

关于ios - 本地通知不适用于设备,但适用于模拟器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28050984/

相关文章:

iOS Facebook SDK v2.0 - 读取另一个用户的公共(public)数据

ios - 如何在后台/终止的 iOS 应用程序中启动进程

ios - iOS 中两个位置之间的估计时间

iphone - 使用 UI 自动化工具删除单元格的语法是什么?

iphone - 如何知道任务是否在后台执行

ios - 为什么将 key 放入 iOS 二进制文件中是安全的

iphone - iOS 6 应用程序 - 如何处理 iPhone 5 的屏幕尺寸?

objective-c - 如何在 Mac OS X 中使用 Storyboard Unwind Segue

android - 做提醒app有什么用?

android - 估计 iBeacon : Monitoring in background (Android)