2015-04-20 25 views
0

每隔一小時,我可以用下面的代碼做手工:運行的功能,每天或斯威夫特

var myDate:NSDateComponents = NSDateComponents() 
    myDate.year = 2015 
    myDate.month = 04 
    myDate.day = 20 
    myDate.hour = 12 
    myDate.minute = 38 
    myDate.timeZone = NSTimeZone.systemTimeZone() 

    var calendar:NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! 
    var date:NSDate = calendar.dateFromComponents(myDate)! 

    var notification:UILocalNotification = UILocalNotification() 
    notification.category = "First Category" 
    notification.alertBody = "Hi, I'm a notification" 
    notification.fireDate = date 

    UIApplication.sharedApplication().scheduleLocalNotification(notification) 

但我怎麼可以運行它每隔一小時或每一天?任何想法?

+0

沒有版本???有小費嗎? –

+0

我的回答對你有幫助嗎? –

回答

0

你的意思是這樣的嗎?

let timer = NSTimer(timeInterval: 3600, target: self, selector: "test", userInfo: nil, repeats: false) 

func test() { 
    // your code here will run every hour 
} 

將所有代碼放在一個類中。更多信息@selector() in Swift?

+3

我不認爲他是什麼意思。如果應用程序關閉,NSTimer將失效。 OP想要某個進程喚醒應用程序並在給定的時間間隔內執行某些代碼序列 –

0

在本地通知repeatInterval上有一個單獨的屬性。見reference

notification.repeatInterval = .Day 

還銘記保持應用程序委託(didFinishLaunchingWithOptions方法)以註冊本地通知(警報請求允許將提交第一次)。在斯威夫特這將是(一個例子):

if UIApplication.instancesRespondToSelector(Selector("registerUserNotificationSettings:")) 
{ 
    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Sound, .Alert, .Badge], categories: nil)) 
} 

我還建議設置時區的通知,可能是這樣的(例子):

notification.timeZone = NSTimeZone.localTimeZone() 

不知道有關「運行功能每...「。這將創建一個以指定重複間隔觸發的通知。我發現這個tutorial有幫助。

0

使用此: -

1)。保存您的每日時間在用戶默認 2)。準時通知第二天 3)。如果時間過去了,請檢查應用程序代理 4)。如果通過,則設置第二天通知 5)。如果更改時間更新用戶默認值

let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true) 


    let request = UNNotificationRequest(identifier: indentifier, content: content, trigger: trigger) 


    UNUserNotificationCenter.current().add(request, withCompletionHandler: { 
     (errorObject) in 
     if let error = errorObject{ 
      print("Error \(error.localizedDescription) in notification \(indentifier)") 
     } 
    })