簡體   English   中英

設置UILocalNotification的fireDate

[英]set fireDate of UILocalNotification

我在這里使用這個應用程序它適用於我,但我想手動插入本地通知的fireDate而不是使用datePicker。

notif.fireDate = [datePicker date];

如何手動插入日期(日,月,年,小時和分鍾)?

我嘗試了以下內容

NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:10];
[dateComps setMonth:3];
[dateComps setYear:2013];
[dateComps setHour:4];
[dateComps setMinute:45];
NSDate *itemDate = [calendar dateFromComponents:dateComps];

int minutesBefore = 2;
notif.fireDate = [itemDate addTimeInterval:-(minutesBefore*60)];

但它不適合我。

提前致謝。

使用NSDateFormatter,您可以直接從NSString轉換為NSDate 這是一個例子:

NSDateFormatter* myFormatter = [[NSDateFormatter alloc] init];
[myFormatter setDateFormat:@"MM/dd/yyyy"];
NSDate* myDate = [myFormatter dateFromString:@"8/26/2012"];
NSLog(@"%@", myDate);  

編輯
如果你也想要時間

NSString *str =@"3/15/2012 9:15 PM";
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"MM/dd/yyyy hh:mm a"];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[formatter setTimeZone:gmt];
NSDate *date = [formatter dateFromString:str];

NSLog(@"%@",date);  

請點擊此鏈接獲取更多信息SO答案

而對於localNotification,也只是在開火日期之后實現這一點

UIApplication *app=[UIApplication sharedApplication];
[app scheduleLocalNotification:localNotification];

使用addTimeInterval怎么addTimeInterval

UILocalNotification *localNotif = [[UILocalNotification alloc] init];
localNotif.fireDate = [itemDate addTimeInterval:-(minutesBefore*60)]; 

 //minutesBefore will be type of int and itemDate would be of NSDate type.

更新1:

搜索后我發現addTimeInterval在iOS 4中已被棄用。 相反,您應該使用dateByAddingTimeInterval

 localNotif.fireDate = [itemDate dateByAddingTimeInterval:-(minutesBefore*60)]; 

提供負值dateByAddingTimeInterval提早火通知分鍾itemDate

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM