2017-04-19 53 views
0

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

回答

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) 
} 

最后,处理你得到的回应并打开链接。而已!

+0

当您在“didFinishLaunching”中设置firstLaunch = false ...它在“didEnterBackground()”中怎么会是真的?或者我错过了什么? – OliverM

+0

的确如此。你有没有尝试过我的代码?对我来说,它自动地工作。如果没有,那么在通知被安排或正在读取firstLaunch之后,您可以将这两行移动到'applicationDidEnterBackground()'。让我知道那是怎么回事! – LinusGeffarth

相关问题