2016-04-20 30 views
0

我希望能夠點擊「從現在開始1分鐘」或「從現在開始1小時」的按鈕,並且通知關閉(推送/橫幅)。我如何去做這件事?如何從現在起X分鐘發出通知?

+0

後延遲後使用performSelector通知! –

+1

@ Teja Nandamuri - 但如果應用程序在一個小時之內不在前臺?然後performSelector不會執行。 noobprogrammer,我相信你可以很容易地找到關於如何創建通知或過去的問題的文檔。可以設置通知觸發的時間。 – Gruntcakes

+1

[在Swift 2中爲特定時間安排本地通知]的可能重複(http://stackoverflow.com/questions/31043458/schedule-a-local-notification-for-a-specific-time-in-swift- 2) – ZGski

回答

1

設定計時器根據按鈕點擊如果1分鐘或1個小時使用下面的命令

NSTimer.scheduledTimerWithTimeInterval(time, target: self, selector: #selector(functionName), userInfo: nil, repeats: true) 

然後廣播在該功能的通知等中的ViewController如下所示

NSNotificationCenter.defaultCenter().postNotificationName("youFunctionName", object: nil) 

的addObserver其中你想收到通知

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(youFunctionName), name: "youFunctionName", object: nil) 
0

在這裏你去,hav寫過代碼安排本地通知:

//First register for User Settings if iOS8 or above 
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 
... 
    if #available(iOS 8, *) { 
      application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Sound, .Alert, .Badge], categories: nil)) 
    } 
... 
return true 
} 

//Function to schedule the local notification 
func scheduleNotificationWithInterval(secondsAfter:Double, notificationTitle title:String, notificationBody body:String) { 

    let fireDate = NSDate() 

    let localNotif = UILocalNotification() 

    localNotif.fireDate = fireDate.dateByAddingTimeInterval(secondsAfter) 

    localNotif.alertBody = body 

    if #available(iOS 8.2, *) { 
      localNotif.alertTitle = title 
    } 

    localNotif.soundName = UILocalNotificationDefaultSoundName; 
    localNotif.applicationIconBadgeNumber = 1; 

    UIApplication.sharedApplication().scheduleLocalNotification(localNotif) 

} 

希望它能幫助:]