每日通知 Swift 3 [英] Daily notifcations Swift 3

查看:64
本文介绍了每日通知 Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何在没有用户输入的情况下每天在特定时间(比如早上 8 点)发送一次通知,并使用新的 UNMutableNotificationContent 而不是已弃用的 UILocalNotification 而不是使用用户输入来触发它,而是使用时间.所有的解释如果发现是旧的,不包括 ios 10 和 swift 3.

I'm trying to figure out how to send a notification once a day at a specific time (say 8am) without user input and using the new UNMutableNotificationContent instead of the deprecated UILocalNotification and not using user input to trigger it but rather a time. All of explanations If found are old and don't include ios 10 and swift 3.

到目前为止我所拥有的.

What I have so far.

ViewController.swift 中的授权通知:

Authorized Notifications in ViewController.swift:

override func viewDidLoad() {

        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in
        })
    }

Notification.swift

Notification.swift

let localNotification = UNMutableNotificationContent()
//    localNotification.fireDate = dateFire
    localNotification.title = "title"
    localNotification.body = "body"
    localNotification.badge = 1
    localNotification.sound = UNNotificationSound.default()

我知道我必须设置触发器和请求等,但我不确定如何让它工作.

I know I have to set a trigger and request among other things but im not sure exactly how to get it to work.

推荐答案

第一步:

import UserNotifications

并判断用户是否允许通知

And to judgement whether the user allows notification

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
granted, error in
    if granted {
        // determine whether the user allows notification
    }
}

第二步:

创建通知

// 1. create notification's content
let content = UNMutableNotificationContent()
content.title = "Time Interval Notification"
content.body = "My first notification"

// 2. create trigger
//custom your time in here
var components = DateComponents.init()
components.hour = 8
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)

// 3. send request identifier
let requestIdentifier = "com.xxx.usernotification.myFirstNotification"

// 4. create send request
let request = UNNotificationRequest(identifier: requestIdentifier, content: content, trigger: trigger)

// add request to send center
UNUserNotificationCenter.current().add(request) { error in
    if error == nil {
        print("Time Interval Notification scheduled: \(requestIdentifier)")
    }
}

您可以在 Apple 文档

这篇关于每日通知 Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆