如何发送本地通知

时间:2015-02-04 19:39:41

标签: ios objective-c

我试图在目标c中发送通知,但我无法弄清楚如何。

到目前为止我已经

    - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    if(self.username != nil)
    {
        NSLog(@"Background fetch username: %@", self.username);
        [self fetchNotifications];
    }


    completionHandler(UIBackgroundFetchResultNewData);
}
- (void)fetchNotifications
{
    NSURL *url = [NSURL URLWithString:
                  [NSString stringWithFormat:@"%@%@",
                   @"https://myurl?username="
                   , self.username]];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response,
                                               NSData *data, NSError *connectionError)
     {
         if (data.length > 0 && connectionError == nil)
         {
             NSDictionary *notifications = [NSJSONSerialization JSONObjectWithData:data
                                                                           options:0
                                                                             error:NULL];

             int nbMessages = [[notifications objectForKey:@"NbOfUnreadMessage"] intValue];
             int nbOfNewMatch = [[notifications objectForKey:@"NbOfNewMatch"] intValue];
             int nbOfNewPlanification = [[notifications objectForKey:@"NbOfNewPlanification"] intValue];
             //int nbMessages = [[notifications objectForKey:@"NbOfUnreadMessage"] intValue];

             NSLog(@"Notifications - nbMessage: %i",nbMessages);
             NSLog(@"Notifications - nbNewMatch: %i",nbOfNewMatch);
             NSLog(@"Notifications - nbNewPlan: %i",nbOfNewPlanification);

             // Schedule the notification
             UILocalNotification* localNotification = [[UILocalNotification alloc] init];
             localNotification.fireDate = nil;
             localNotification.alertBody = @"test";
             localNotification.alertAction = @"Show me the item";
             localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;

             [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
         }
     }];
}

当我尝试使用IOS 8.1的iPhone 6模拟器时,我有以下错误

  

尝试标记应用程序图标但尚未获得用户的许可以标记应用程序

我必须阅读并理解这个post

但我真正的问题是当我使用iPhone 5 IOS 7.1模拟器时,甚至没有调用函数fetchNotifications

为什么只在IOS 8.1下调用fetchNotifications

在OS

下调用

performFetchWithCompletionHandler

1 个答案:

答案 0 :(得分:0)

  

尝试标记应用程序图标但尚未获得用户的许可以标记应用程序

是Xcode告诉您在模拟器上运行时无法更改通知徽章值的方式。不允许

iOS决定时调用此委托方法。来自UIApplicationDelegate文档:

  

当有机会下载数据时,系统会调用此方法为您的应用提供下载所需数据的机会。更重要的是,系统使用经过的时间来计算应用程序后台下载的功耗和数据成本。如果您的应用程序需要很长时间才能调用完成处理程序,那么将来获取数据的机会可能会更少。