2017-04-19 1 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

관련 문제