我目前正在创建一个支持iOS 8及更高版本的应用。在我的应用中,我想做每日通知,如“当天的话”。所以我尝试了localNotification,因为iOS 8-9正在使用UILocalNotification,而ios10正在使用NSNotificationcenter。但我现在卡住了,因为我试图传递alertBody中的变量。它是打印空的,因为我从url会话请求得到它的那天的话。所以我想知道,我该怎么做?请帮忙!
答案 0 :(得分:0)
您可以使用本地通知来获取每日通知。
let notification = UILocalNotification()
notification.fireDate = date
notification.alertBody = "Alert!"
notification.alertAction = "open"
notification.hasAction = true
notification.userInfo = ["UUID": "reminderID" ]
notification.repeatInterval = NSCalendarUnit.CalendarUnitDay
UIApplication.sharedApplication().scheduleLocalNotification(notification)
使用KCFCalenderUnitDay,您的通知每天都会被触发,但正如您所提到的,您需要从服务器获取每天的响应,用户需要单击通知。如果没有单击或用户交互,则不会调用此方法。在此方法中,您可以调用您的服务并再次设置本地通知。
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
let state : UIApplicationState = application.applicationState
if (state == .Inactive || state == .Background) {
// go to screen relevant to Notification content
} else {
// App is in UIApplicationStateActive (running in foreground)
}
}
将日期设定为上午9点
let date: NSDate = NSDate()
let cal: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)!
cal.timeZone = NSTimeZone(name: "GMT")!
let newDate: NSDate = cal.dateBySettingHour(9, minute: 0, second: 0, ofDate: date, options: NSCalendarOptions())!
添加天数
NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
dayComponent.day = 1;
NSCalendar *theCalendar = [NSCalendar currentCalendar];
NSDate *nextDate = [theCalendar dateByAddingComponents:dayComponent toDate:[NSDate date] options:0];
//Swift
var tenDaysfromNow: Date {
return (Calendar.current as NSCalendar).date(byAdding: .day, value: 10, to: Date(), options: [])!
}