0

我想知道如何在我的應用程序的NSTimer在後臺觸發時獲取本地通知。我的NSTimer在後臺每隔10分鐘檢查一次文件夾的文件。如果找到文件,我將如何去接收本地通知?如果確定文件夾不是空的,如何獲取本地通知?

編輯:代碼:

- (void) createTimeThread: (float) pIntervalTime 
{ 
    [NSThread detachNewThreadSelector:@selector(startTimerThread) 
          toTarget:self withObject:nil]; 
} 

- (void) startTimerThread 
{ 
    UIBackgroundTaskIdentifier bgTask = [[UIApplication sharedApplication] 
             beginBackgroundTaskWithExpirationHandler:^{}]; 

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    NSRunLoop* runLoop = [NSRunLoop currentRunLoop]; 

    myTimer = [NSTimer scheduledTimerWithTimeInterval:1 
               target:self 
              selector:@selector(conditionChecking:) 
              userInfo:nil 
               repeats:YES]; 

    [runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; 
    [pool release]; 

    [[UIApplication sharedApplication] endBackgroundTask:bgTask]; 
} 

- (void)conditionChecking:(NSIndexPath *)indexPath 
{ 
    NSString *pathForFile = @"/User/Library/Logs/CrashReporter"; 

    NSFileManager *fileManager = [NSFileManager defaultManager]; 

    if ([fileManager fileExistsAtPath:pathForFile]) { // Directory exists 
     NSArray *listOfFiles = [fileManager contentsOfDirectoryAtPath:pathForFile error:nil]; 

     if (!listOfFiles || !listOfFiles.count) 
     { 
      NSLog(@"No Core Dumps found....."); 
     } 
     else 
     { 
      NSLog(@"Core Dump(s) found! :%@", listOfFiles); 
     } 
    } 
} 
+1

您的標籤與您的問題衝突 - 您是要求推送通知還是本地通知? – BoltClock

+0

不明白你的問題是什麼。您是否正在尋找'NSTimer'的替代品,或者只是想知道如果發現文件時如何通知? – Saphrosit

+0

我只想知道如何在後臺獲取通知。 –

回答

0

我相信,您要通知該文件夾中充滿了文件中的所有其他類。

以下步驟可以爲您做到這一點。

  1. 在要接收通知的類的初始化中寫入以下行。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkFiles:) name:@"FILES_AVAILABLE" object:nil];

  1. 寫入方法checkFiles與同級別以下簽名。

    -(void)checkFiles:(id)sender

  2. 添加如下的計時器類線的時候文件可用。

    [[NSNotificationCenter defaultCenter] postNotificationName:@"FILES_AVAILABLE" object:self];

如果這是沒有幫助的,那麼你可以使用NSUserDefault存儲應用程序的狀態(文件是可用的或者沒有你的情況下)。或者如果您對設計模式感興趣,請閱讀Observer Pattern。

如果您想要在應用程序處於後臺模式時發佈通知,並且仍在運行的某個進程獲取某些更新,那麼可以使用通知隊列來實現。閱讀以下鏈接。我不寫代碼,因爲代碼是在鏈接本身給出的。

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Notifications/Articles/NotificationQueues.html#//apple_ref/doc/uid/20000217-CJBCECJC

郵政在這裏如果你需要更多的幫助。

+0

其實,我只是想在後臺通知用戶。通知應該喚醒電話並且有兩個按鈕,這兩個按鈕都是可控的。意思我應該能夠控制它們,比如我將如何控制UIAlertView中的按鈕(通過向它們添加邏輯) –

+0

希望這會有所幫助...... http://developer.apple.com/library/mac/#documentation/可可/概念/通知/用品/ NotificationQueues.html#// apple_ref/DOC/UID/20000217-CJBCECJC – Mohammad

相關問題