2016-01-03 74 views
0

嘗試以swift方式發送每日本地通知。然而,由於某種原因,它只發送每一分鐘。我希望第一次通知在應用程序打開後30分鐘發送,然後每天重複此通知。Swift iOS 9.2中的每日本地通知

在迅速FIE我有以下代碼

// ---------日用品的通知代碼(也應用delagate添加部分---------- 讓theDate = NSDate的()

let dateComp = NSDateComponents() 
    dateComp.minute = 30 

    let cal = NSCalendar.currentCalendar() 

    let fireDate:NSDate = cal.dateByAddingComponents(dateComp , toDate: theDate, options: NSCalendarOptions(rawValue: 0))! 


    let notification:UILocalNotification = UILocalNotification() 

    //choosing what it says in the notification and when it fires 
    notification.alertBody = "Your Daily Motivation is Awaits" 

    notification.fireDate = fireDate 


    UIApplication.sharedApplication().scheduleLocalNotification(notification) 

    //displaying notification every day 
    notification.repeatInterval = NSCalendarUnit.Day 



    //-------------end of daily notification code--------------- 
在我的應用程序委託文件

我有以下代碼:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 

    //----------daily notification section ---------- 
    let notiftypes:UIUserNotificationType = UIUserNotificationType.Alert.union(UIUserNotificationType.Badge).union(UIUserNotificationType.Sound) 

    let notifSettings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notiftypes, categories: nil) 

    UIApplication.sharedApplication().registerUserNotificationSettings(notifSettings) 

    return true 
    //----------end of daily notification section----------- 
} 

回答

1

的問題是,你正在計劃的通知後,設定重複間隔Ĵ烏斯季設置的通知財產scheduleLocalNotification之前,確保你安排它只有一次:

let notification = UILocalNotification() 
notification.alertBody = "Your Daily Motivation is Awaits" 
// You should set also the notification time zone otherwise the fire date is interpreted as an absolute GMT time 
notification.timeZone = NSTimeZone.localTimeZone() 
// you can simplify setting your fire date using dateByAddingTimeInterval 
notification.fireDate = NSDate().dateByAddingTimeInterval(1800) 
// set the notification property before scheduleLocalNotification 
notification.repeatInterval = .Day 
UIApplication.sharedApplication().scheduleLocalNotification(notification) 

注:UIUserNotificationType是OptionSetType結構,所以還可以簡化其聲明:

let notiftypes:UIUserNotificationType = [.Alert, .Badge, .Sound]