2009-09-21 262 views
2

在iPhone SDK 3.0註冊通知,我想對於一個註冊通知,當達到一定的時候,它會提醒我的應用程序。可能嗎? 感謝在iPhone SDK 3.0

+0

你的意思是推送通知,或NSNotification? NSNotification很容易,但不完全是你需要的。至於推送通知,我從來沒有真正掌握過它們。 – 2009-09-21 06:06:29

回答

1

假設你已經在變量date一個NSDate,並希望在該日期就火法dateIsHere:,這樣做:

NSTimer* timer = [[NSTimer alloc] initWithFireDate:date 
              interval:0.0f 
              target:self 
              selector:@selector(dateIsHere:) 
              userInfo:nil 
              repeats:NO]; 
[[NSRunLoop mainRunLoop] addTimer:timer 
          forMode:NSDefaultRunLoopMode]; 
[timer release]; 
+0

嗨PeyloW, 我以下面的方式嘗試了你的代碼,但我得到了一個N​​SInvalidArgumentException.Can你可以告訴我我在這裏做什麼不正確 ---此代碼是在不同的函數內 NSDate * date = [[NSDate alloc ]在裏面]; \t日期= [NSDate的日期]; \t的NSTimer *計時器= [[ALLOC的NSTimer] initWithFireDate:日期 \t \t \t \t \t間隔:0。0F \t \t \t \t \t目標:自 \t \t \t \t選擇器:@selector(dateIsHere :) \t \t \t \t \t USERINFO:無 \t \t \t \t \t重複:NO]; \t [[NSRunLoop mainRunLoop] addTimer:timer \t \t \t forMode:NSDefaultRunLoopMode]; (無效)dateIsHere { \t NSLog(@「Date is here」); } 謝謝 – felix 2009-09-22 05:09:16

+0

我發現了這個問題。我必須有dateIsHere funtcion lik dateIsHere:(NSTimer *)計時器。我沒有包括計時器參數。:) – felix 2009-09-22 05:31:30

0

您將通過設置一個NSTimer開始火在某個日期,並選擇該火災可能是你想要的。不需要使用NSNotifications。

5

建立一個運行選擇的NSTimer每30秒(或任何你需要的粒度):

[NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES]; 

-timerFired:選擇器(方法)將運行每隔30秒,檢查小時,分鐘和第二部件,發射一個通知,如果元素匹配所需的時間:

- (void) timerFired:(NSNotification *)notification { 
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
    NSCalendarUnit unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit; 
    NSDate *date = [NSDate date]; 
    NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date]; 
    NSInteger hour = [dateComponents hour]; 
    NSInteger min = [dateComponents minute]; 
    NSInteger sec = [dateComponents second]; 
    if ((hour == kDesiredHour) && (min == kDesiredMinute) && (sec == kDesiredSecond)) { 
     [[NSNotificationCenter defaultCenter] postNotificationName:@"kTimeComponentsWereMatched" object:nil userInfo:nil]; 
    } 
} 

您註冊偵聽此通知在其他一些地方類:

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

因此,你必須在同一類中的方法,做一些有趣的事情:

- (void) doSomething:(NSNotification *)notification { 
    // do something interesting here... 
} 

如果是在同一個類可以合併該代碼。或者在NSTimer中指定target指向要運行selector的類實例。

+0

確實,即使應用程序被關閉這項工作? – cone 2011-08-18 08:27:53

1

我假設您希望此計時器觸發,即使應用程序已關閉。您可以使用通知,但您必須擁有發佈通知的服務器。

此外,iPhone會拉一個警報,要求用戶打開應用程序 - 但他們沒有選擇這樣做。