Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active June 23, 2018 22:50
Show Gist options
  • Save KentarouKanno/9faf13f5a0ca8e88cf72 to your computer and use it in GitHub Desktop.
Save KentarouKanno/9faf13f5a0ca8e88cf72 to your computer and use it in GitHub Desktop.
UILocalNotification

UILocalNotification

★ 通知の初期化(ユーザーへの許可を促す)

let settings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
UIApplication.shared.registerForRemoteNotifications()

★ 通知を作成

@IBAction func setLocalNotification(sender: UIButton) {
    
    let notification = UILocalNotification()
    // 10秒後に通知
    notification.fireDate = Date(timeIntervalSinceNow: 5)
    notification.timeZone = NSTimeZone.default
    notification.alertBody = "Alert Body"
    notification.alertAction = "OK"
    
    // Dictionary Data
    notification.userInfo = ["key": "value", "time": Date()]
    
    // Custom Sound
    notification.soundName = "sample.mp3";
    // Default Sound
    notification.soundName = UILocalNotificationDefaultSoundName
    UIApplication.shared.scheduleLocalNotification(notification);
}

★ 位置情報を利用したローカル通知

let localNotify = UILocalNotification()

localNotify.alertBody = "まもなく目的地!"
localNotify.soundName = UILocalNotificationDefaultSoundName
localNotify.applicationIconBadgeNumber = 1;

let location = CLLocationCoordinate2DMake(35.658581, 139.745433);
// 緯度経度と位置からの半径を設定
let region = CLCircularRegion(center: location, radius: 1000.0, identifier: "Identifier")
region.notifyOnExit = false

if #available(iOS 8.0, *) {
    localNotify.region = region
    localNotify.regionTriggersOnce = false
}

UIApplication.sharedApplication().scheduleLocalNotification(localNotify)

★ ローカル通知を受信時に内容を取得

// didFinishLaunchingWithOptionsで取得する場合

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    
    if let notification = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification {
        
        if let body = notification.alertBody {
            //=> Alert Body
        }
        
        if let notify = notification.userInfo {
            //=> [key: value, time: 2016-02-18 15:22:46 +0000]
        }
    }
    
    return true
}

// didReceiveLocalNotificationで取得する場合

func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
    
    if let body = notification.alertBody {
        //=> Alert Body
    }
    
    if let notify = notification.userInfo {
        //=> [key: value, time: 2016-02-18 15:22:46 +0000]
    }
}

★ アプリ起動中にローカル通知を受けた時に現在表示中のViewControllerにアラートを表示する

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        let settings = UIUserNotificationSettings(forTypes: [.Badge, .Sound, .Alert], categories:nil)
        UIApplication.sharedApplication().registerUserNotificationSettings(settings)
        UIApplication.sharedApplication().registerForRemoteNotifications()
        
        return true
    }
    
    func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
        
        if application.applicationState == .Active {
            
            if let title = notification.alertTitle, let body = notification.alertBody {
                let alert = UIAlertController(title: title, message: body, preferredStyle: .Alert)
                alert.addAction( UIAlertAction(title: "OK", style: .Default, handler: nil))
                UIApplication.sharedApplication().topViewController()?.presentViewController(alert, animated: true, completion: nil)
            }
        }
    }
}


extension UIApplication {
    func topViewController() -> UIViewController? {
        guard var topViewController = UIApplication.sharedApplication().keyWindow?.rootViewController else { return nil }
        
        while let presentedViewController = topViewController.presentedViewController {
            topViewController = presentedViewController
        }
        return topViewController
    }
}

★ ローカル通知の設定状況を取得する

if #available(iOS 8.0, *) {
    // iOS8.0->
    
    let status = UIApplication.sharedApplication().currentUserNotificationSettings()?.types
    if let status = status where status == UIUserNotificationType.None {
        print("Notification None")
    } else {
        
        if let status = status {
            if status.contains(UIUserNotificationType.Badge) {
                print("Badge ON")
            }
            if status.contains(UIUserNotificationType.Sound) {
                print("Sound ON")
            }
            if status.contains(UIUserNotificationType.Alert) {
                print("Alert ON")
            }
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment