iOS:如何在用户暂停应用时通知/提醒用户?

时间:2017-04-19 17:49:55

标签: ios parse-platform push-notification uilocalnotification

我的任务是实施一项功能,在首次暂停应用时向合格用户发送指向在线调查的链接。理想情况下,我会使用某种类型的通知(例如本地,推送)来执行此操作。有没有办法让应用程序在用户暂停时触发通知,以便点击它会打开调查链接(可能首先通过重新启动应用程序)?

1 个答案:

答案 0 :(得分:0)

AppDelegate中,您需要保存用户之前是否曾打开过该应用。

<强>的AppDelegate

//make sure to import the framework
//additionally, if you want to customize the notification's UI,
//import the UserNotificationsUI
import UserNotifications

//default value is true, because it will be set false if this is not the first launch
var firstLaunch: Bool = true
let defaults = UserDefaults.standard

//also make sure to include *UNUserNotificationCenterDelegate*
//in your class declaration of the AppDelegate
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

//get whether this is the very first launch
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    if let bool = defaults.object(forKey: "firstLaunch") as? Bool {
        firstLaunch = bool
    }
    defaults.set(false, forKey: "firstLaunch")
    defaults.synchronize()

    //ask the user to allow notifications
    //maybe do this some other place, where it is more appropriate
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in}

    return true
}

//schedule your notification when exiting the app, if necessary
func applicationDidEnterBackground(_ application: UIApplication) {
    //update the variable
    if let bool = defaults.object(forKey: "firstLaunch") as? Bool {
        firstLaunch = bool
    }
    if !firstLaunch {
        //abort mission if it's not the first launch
        return
    }
    //customize your notification's content
    let content = UNMutableNotificationContent()
    content.title = "Survey?"
    content.body = "Would you like to take a quick survey?"
    content.sound = UNNotificationSound.default()

    //schedule the notification
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
    let request = UNNotificationRequest(identifier: "takeSurvey", content: content, trigger: trigger)
    let center = UNUserNotificationCenter.current()
    center.add(request, withCompletionHandler: nil)
}

最后,处理您的回复并打开您的链接。那就是它!