2017-03-19 28 views
2

私はスケジュールを作成しようとしています。そのスケジュールでは、特定の時間に月曜などのクラスを覚えておく必要があります。問題は、変数triggerWeeklyを出力するときにweekday = 1(日曜日)を割り当てると、weekday = 2と表示されるため、テストを実行すると通知は得られません。私は、これは週3回のトリガー通知Swift 3

let weekday = 1 //Sunday 19 Mar 
let calendar = NSCalendar.current 
var date = DateComponents() 
date.weekday = weekday 
date.hour = 1 
date.minute = 5 

let ultimateDate = calendar.date(from: date) 

let triggerWeekly = Calendar.current.dateComponents([.weekday, .hour, .minute], from: 
ultimateDate!) 

print(triggerWeekly) // hour: 1 minute: 5 second: 0 weekday: 2 isLeapMonth: false 
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true) 
let identifier = "curso\(String(Index))" 
let request = UNNotificationRequest(identifier: identifier, 
             content: content, trigger: trigger) 
+1

それは –

+1

この '聞かせてトリガ= UNCalendarNotificationTriggerのようにしてみてください(笑)午前1時でした(dateMatching:DateComponents(時間:1分:5、平日:2)、繰り返される:真)' –

+0

ありがとう:)私はそれを試してみます –

答えて

6

をなぜ起こるかあなたは次のように1:05で毎週月曜日を繰り返すために、あなたのトリガーを設定することができます知っておく必要があります。

import UserNotifications 

let trigger = UNCalendarNotificationTrigger(dateMatching: DateComponents(hour: 1, minute: 5, weekday: 2), repeats: true) 
print(trigger.nextTriggerDate() ?? "nil") 

let content = UNMutableNotificationContent() 
content.title = "title" 
content.body = "body" 
// make sure you give each request a unique identifier. (nextTriggerDate description) 
let request = UNNotificationRequest(identifier: "identify", content: content, trigger: trigger) 
UNUserNotificationCenter.current().add(request) { error in 
    if let error = error { 
     print(error) 
     return 
    } 
    print("scheduled") 
} 

で通知をスケジュールするユーザーの許可を求めることを忘れないでください。あなたのAppDelegate:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
    // Override point for customization after application launch. 
    UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]) { granted, error in 
     // your code 
    } 
    return true 
} 
+0

ありがとう!それは動作します:) –

+0

あなたは歓迎です –

+0

@LeoDabus関数呼び出しに基づいてnotifucationをトリガする方法を教えてもらえますか?いつでも私たちはバナー通知を表示するためにその関数を呼び出します。 –

関連する問題