Ios 在后台收到Api响应时如何使用本地通知?

Ios 在后台收到Api响应时如何使用本地通知?,ios,notifications,nstimer,uilocalnotification,Ios,Notifications,Nstimer,Uilocalnotification,我的应用程序使用谷歌地图,它显示汽车的方向,这样用户就可以看到它在地图上移动,我的问题是: 1.当用户将应用程序放在后台时,我希望NSTimer保持运行 2.当它在后台时,当我收到api的响应,汽车到达时,我想发送一个本地通知,以便用户可以看到它并打开应用程序 下面是一些代码: //here is the timer searchTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(ge

我的应用程序使用谷歌地图,它显示汽车的方向,这样用户就可以看到它在地图上移动,我的问题是: 1.当用户将应用程序放在后台时,我希望NSTimer保持运行 2.当它在后台时,当我收到api的响应,汽车到达时,我想发送一个本地通知,以便用户可以看到它并打开应用程序

下面是一些代码:

//here is the timer 
searchTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(getLocationForDriver) userInfo:Nil repeats:YES];

-(void)getLocationForDriver
{
NSArray* pks = [NSArray arrayWithObject:self.driverPK];

[[NetworkEngine getInstance] trackBooking:pks completionBlock:^(NSObject* response)
 {

     NSDictionary* dict = (NSDictionary*)response;
     currentStatus = [dict objectForKey:@"current_status"];

.
.
.
.
   if ([currentStatus isEqualToString:@"completed"])
     {
       //here i want to send the local notification
     }

 }
}

通常,当一个应用程序被发送到后台时,系统很快就会终止它。例外的是一款应用程序,它符合苹果的
UIBackgroundModes
(我建议你多读一些,特别是关于长时间运行的后台任务的部分)。这是一种机制,允许需要在后台运行长任务的应用程序在不被终止的情况下运行(导航应用程序、VoIP应用程序、音乐应用程序…)

根据您的问题,您的应用程序将使用位置更新后台模式似乎是合理的。要启用此模式,您需要转到目标->功能,将背景模式打开并选中位置更新框。 一旦您完成此操作,您的应用程序将不会在发送到后台后终止,并且您应该能够运行
NSTimer
,获得api响应并像平时一样发送通知

请记住,您的应用程序需要使用其中一种后台模式的充分理由,否则将被应用程序商店拒绝

更新

要发送本地通知,可以在代码中添加以下行:

if ([currentStatus isEqualToString:@"completed"])
     {
        UILocalNotification* localNotification = [[UILocalNotification alloc] init];
        localNotification.fireDate = [NSDate date];
        localNotification.alertBody = @"My notification text";
        localNotification.timeZone = [NSTimeZone defaultTimeZone];
        localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
       [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
     }
这会立即发送本地通知,并将+1添加到应用程序的图标徽章中。(您可以阅读有关
UILocalNotification
和的更多信息) 如果在触发通知时您的应用程序正在后台运行,则用户将在屏幕顶部看到作为横幅的通知


然后,您可以通过实现应用程序委托的
application:didReceiveLocalNotification:
方法来处理通知。请记住,如果您的应用程序在后台运行,则只有当用户通过单击通知横幅或应用程序图标将应用程序带到前台时,才会调用此方法。

这有助于解决计时器的第一个问题,,但主要问题是如何在使用UILocalnotification收到响应时发送通知?