본문 바로가기

Mobile/IOS & Swift

[swift3] UserNotifications IOS10 새기능 사용해보기

[swift3] UserNotifications

ios10 UserNotifications

ios10부터 UserNotification이 생겼다. 이제 조금 더 쉽게 사용자에게 메세지를 보낼 수 있다.


먼저 중앙에 버튼을 만들어보자

기본텍스트 출력

ViewController.swift

class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//
// alert, badge, sound .
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound], completionHandler: {(granted,error) in
//permission true
if granted{
print("Notification access granted")
}else{
print(error?.localizedDescription as Any)
}
})
}
//
@IBAction func notifyButtonTapped(sender: UIButton){
// !
//scheduleNotification
scheduleNotification(inSeconds: 5, completion: {success in
if success{
print("")
}else{
print("error")
}
})
}
// notification
//@escaping .
func scheduleNotification(inSeconds: TimeInterval, completion: @escaping (_ Success: Bool) -> ()){
// .
let notif = UNMutableNotificationContent()
notif.title = ""
notif.subtitle = " !"
notif.body = "ios10 !"
// .
let notiTrigger = UNTimeIntervalNotificationTrigger(timeInterval: inSeconds, repeats: false)
// request .
let request = UNNotificationRequest(identifier: "myNotification", content: notif, trigger: notiTrigger)
// notification .
UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
if error != nil{
print(error?.localizedDescription as Any)
completion(false)
}else{
completion(true)
}
})
}
}


스샷을 찍는걸 깜박하여.. 대략적인 모습은 아래와 같다.
버튼 클릭 후 cmd + shift + h 를 빠르게 누르자.

커스텀 이미지를 추가하자

ViewController.swift

//
// notification
//@escaping .
func scheduleNotification(inSeconds: TimeInterval, completion: @escaping (_ Success: Bool) -> ()){
// . gif ..
guard let imageUrl = Bundle.main.url(forResource: "rick_grimes", withExtension: "gif")else{
completion(false)
return
}
//attachment
var attachment: UNNotificationAttachment
// imageUrl .
attachment = try! UNNotificationAttachment(identifier: [], url: imageUrl, options: .none)
let notif = UNMutableNotificationContent()
notif.title = ""
notif.subtitle = " !"
notif.body = "ios10 !"
//attachment
notif.attachments = [attachment]
let notiTrigger = UNTimeIntervalNotificationTrigger(timeInterval: inSeconds, repeats: false)
// ..

위와 같이 이미지가 출력되는걸 볼 수 있다.

홈버튼 안누르고 notification띄우기

appDelegate.swift

import UIKit
//UserNotification
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
//UserNotification delegate
UNUserNotificationCenter.current().delegate = self
}
///
// UserNoti .
//Notification completionHandler alert .
extension AppDelegate: UNUserNotificationCenterDelegate{
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(.alert)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print(" : \(response.actionIdentifier)")
completionHandler()
}
}
//

custom 형태의 notification 띄우기

file -> new -> target을 통해 Notification Content Extension을 만들자

스토리 보드에서 view 크기를 키워준 후 이미지뷰와 텍스트를 넣었다

기존

수정후

NotificationViewController.swift

import UIKit
import UserNotifications
import UserNotificationsUI
class NotificationViewController: UIViewController, UNNotificationContentExtension {
//
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any required interface initialization here.
}
func didReceive(_ notification: UNNotification) {
//
guard let attachment = notification.request.content.attachments.first else{
return
}
// url access
if attachment.url.startAccessingSecurityScopedResource(){
//attachment.url imageData url
let imageData = try? Data.init(contentsOf: attachment.url)
//imageData img
if let img = imageData{
// .
imageView.image = UIImage(data: img)
}
}
}
}

appDelegate.swift

//
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
private func configureUserNotifications(){
// notification
let catagory = UNNotificationCategory(identifier: "myNotificationCategory", actions: [], intentIdentifiers: [], options: [])
//
UNUserNotificationCenter.current().setNotificationCategories([catagory])
}
//

ViewController.swift

//
var attachment: UNNotificationAttachment
attachment = try! UNNotificationAttachment(identifier: "myNotification", url: imageUrl, options: .none)
let notif = UNMutableNotificationContent()
//custom view
notif.categoryIdentifier = "myNotification"
notif.title = ""
notif.subtitle = " !"
notif.body = "ios10 !"
//notification
let request = UNNotificationRequest(identifier: "myNotification", content: notif, trigger: notiTrigger)

익스텐션의 info.plist


UNNotificationExtensionCategory에 myNotificationCategory 추가

버튼 넣는건 2부에서 계속