๐ง ํธ์ฌ์๋ฆผ์ ์ฌ์ฉํด์ผ ํ ์ผ์ด ์๊ฒจ์ ์ด๋ฒ์ ์ ๋ฆฌํ๊ฒ ๋์๋๋ฐ, ์ฐ์ ๋ก์ปฌ์์ ๋ฐ์ํ๋ ํธ์ฌ์๋ฆผ์ ์ค์ ํด๋ดค์ต๋๋ค.
Step 1
์ฌ์ฉ์์๊ฒ ์๋ฆผ ์ฌ์ฉ์ ๋ํ ํ์ฉ์ ๋ฐ์์ผํฉ๋๋ค. ๊ถํ์ ๋ฐ๊ธฐ ์ํด UNUserNotificationCenter ์ธ์คํด์ค๋ฅผ ํตํด requestAuthorization(options:completionHandler:) ๋ฉ์๋๋ฅผ ์ฌ์ฉํฉ์๋ค.
...
import UserNotifications
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if let error = error {
print("\(Error: \(error.localizedDescription))")
}
granted ? print("Allow") : print("NotAllow")
}
}
}
Step 2
์๋ฆผ ๋ด์ฉ์ ์์ฑํด์ผ ํฉ๋๋ค. UNMutableNotificationContent์ ์ด์ฉํ์ฌ ๋ด์ฉ์ ์์ฑํ ์ ์์ต๋๋ค.
...
class ViewController: UIViewController {
...
private lazy var notificationContent: UNMutableNotificationContent = {
let content = UNMutableNotificationContent()
content.title = "Hello Notification"
content.body = "Study APNs with Apple developer doc"
return content
}()
}
Step 3
์๋ฆผ์ ์ ๊ณตํ๊ธฐ์ํ ์กฐ๊ฑด์ ์ํด ํธ๋ฆฌ๊ฑฐ(๋ฐฉ์์ )๋ฅผ ์์ฑํด์ผ ํฉ๋๋ค. UNCalendarNotificationTrigger, UNTimeIntervalNotificationTrigger, ๋๋ UNLocationNotificationTrigger ๋ฅผ ์ฌ์ฉํ์ฌ ํธ๋ฆฌ๊ฑฐ๋ฅผ ์์ฑํ ์ ์์ต๋๋ค. ์๋์์๋ UNTimeIntervalNotificationTrigger๋ฅผ ์ด์ฉํ์ฌ ์์ฑํด ๋ณด๊ฒ ์ต๋๋ค.
...
class ViewController: UIViewController {
...
private let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)
}
Step 4
์์์ ์์ฑํ ๋ด์ฉ ๋ฐ ํธ๋ฆฌ๊ฑฐ๋ฅผ ํฌํจํ UNNotificationRequest ์์ฒญ์ ๋ง๋ค๊ณ ์์คํ ์ ์์ฑํ ์์ฒญ์ ์์ฝํ๊ธฐ ์ํ add(_:withCompletionHandler:) ๋ฉ์๋๋ฅผ ํธ์ถํด์ผํฉ๋๋ค. ์๋์์๋ ๋ฒํผ์ ์ถ๊ฐํด์ ๋ฒํผ ์ก์ ์ ์์ฒญํ๋ ๋ฉ์๋๋ฅผ ๋ง๋ค์์ต๋๋ค.
...
class ViewController: UIViewController {
...
@IBAction func pushNoti(_ sender: UIButton) {
// Create the request
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString,
content: notificationContent, trigger: trigger)
// Schedule the request with the system.
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.add(request) { (error) in
if error != nil {
// Handle any errors.
}
}
}
}
๐ง(์๋ ์ฐธ๊ณ ๋ด์ฉ์ ํตํด ๋ ์์ธํ ์ ๋ณด๋ฅผ ํ์ธํ ์ ์์ต๋๋ค!)
Apple Developer - Permission
Apple Developer - ReqNotification Locally