2014-01-26 81 views
1

我的應用程序正在使用谷歌地圖,它顯示了汽車方向,使用戶可以看到其移動地圖,我的問題是:1。 當用戶將應用程序在後臺我想要的NSTimer保持運行 2.雖然它在後臺,當我收到來自api的迴應,表示汽車已抵達,,我想發送本地通知,以便用戶可以看到它並打開應用程序如何在後臺接收到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 
    } 

} 
} 

回答

1

通常,當應用程序發送到後臺時,系統會立即終止該應用程序。這個例外是適合Apple的UIBackgroundModes(我建議您閱讀更多關於app states and multitasking的應用程序,特別是關於長時間運行後臺任務的部分)。這是一種機制,允許那些需要在後臺運行的長期任務的應用程序,而不終止這樣做(導航應用,VoIP的應用,音樂應用程序...)

根據您的問題,這似乎是合理的,你的應用程序將使用位置更新背景模式。爲了啓用此模式,您需要轉到您的目標 - >功能,將背景模式打開並檢查位置更新框。 一旦你完成了這個任務,你的應用一旦發送到後臺就不會被終止,你應該可以運行NSTimer,獲得api響應併發送類似你通常那樣的通知。

請記住,您的應用程序需要使用背景模式之一的一個很好的理由,否則會被應用程序商店拒絕。

UPDATE

爲了發送本地通知,可以將下面的行添加到您的代碼:

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到應用程序的圖標徽章。如果您的應用程序在後臺運行時通報解僱,則用戶將看到通知,在屏幕的上方看到橫幅廣告(你可以閱讀更多關於UILocalNotificationherehere) 。

然後,您可以通過實現應用程序委託的application:didReceiveLocalNotification:方法處理的通知。請記住,如果您的應用程序在後臺運行,則只有在用戶通過點擊通知橫幅或應用程序圖標將應用程序置於前臺時,此方法纔會被調用。

+0

那麼,這有助於解決計時器的第一個問題,但主要問題是如何發送通知時,收到使用UILocalnotification響應? – ghasso

+0

查看我更新的答案 – Gad

相關問題