位置情報と連動した通知を表示する（ローカル通知）（UIKit::UIApplication.scheduleLocalNotification）

# ロケーションベースの通知を使う

## 位置情報サービス準備

Info.plistのRequired device capbilitiesにlocation-servicesとgpsを追加
Info.plistの　Information Property ListにNSLocationAlwaysUsageDescriptionを追加して、許可取得時のメッセージ設定

```swift:ViewController.swift
import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    var myLocationManager: CLLocationManager!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        checkLocationAuthorization(startLocationService)
    }

    func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        if status != CLAuthorizationStatus.AuthorizedAlways {
            return
        }
        
        if !CLLocationManager.locationServicesEnabled() {
            return
        }
        
        startLocationService(manager)
    }
    
    func checkLocationAuthorization(callback: (CLLocationManager) -> Void) {
        let status = CLLocationManager.authorizationStatus()
        if status == CLAuthorizationStatus.Restricted || status == CLAuthorizationStatus.Denied {
            return
        }
        
        myLocationManager = CLLocationManager()
        myLocationManager.delegate = self
        
        if status == CLAuthorizationStatus.NotDetermined {
            myLocationManager.requestAlwaysAuthorization()
        } else if !CLLocationManager.locationServicesEnabled() {
            return
        } else {
            callback(myLocationManager)
        }
    }
    
    func startLocationService(manager: CLLocationManager) {
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.distanceFilter = kCLDistanceFilterNone
    }
```

## 通知タイプ登録

```swift:ViewController.swift
    var myLocationManager: CLLocationManager!
    let notificationManager: NotificationManager = NotificationManager.init()
    
// 中略

        startLocationService(manager)
        registerLocationBasedLocalNotification(latitude: 35.7, longitude: 139.6, radius: 100)
    }
    
// 中略

        callback(myLocationManager)
        registerLocationBasedLocalNotification(latitude: 35.7, longitude: 139.6, radius: 100)
    }
    
// 中略

        manager.distanceFilter = kCLDistanceFilterNone
    }
    
    func registerLocationBasedLocalNotification(latitude latitude: CLLocationDegrees, longitude: CLLocationDegrees, radius: CLLocationDistance) {
        let center = CLLocationCoordinate2DMake(latitude, longitude)
        let region = CLCircularRegion.init(center: center, radius: radius, identifier: "YourLocationIdentifier")
        region.notifyOnExit = false
        notificationManager.setLocationBasedLocalNotification(region: region, alertAction: "Alert Action", alertBody: "到着", soundName: UILocalNotificationDefaultSoundName)
    }
```

```swift:NotificationManager
import UIKit
import CoreLocation

public class NotificationManager: NSObject {
    
    override
    init() {
        let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
        
        UIApplication.sharedApplication().registerUserNotificationSettings(settings)
    }
    
    func setLocationBasedLocalNotification(
        region region: CLCircularRegion,
               regionTriggersOnce: Bool = true,
               alertAction: String? = nil,
               alertBody: String? = nil,
               alertTitle: String? = nil,
               hasAction: Bool = true,
               applicationIconBadgeNumber: Int = 0,
               soundName: String? = nil,
               userInfo: NSDictionary? = nil)
    {
        let localNotification = UILocalNotification.init()
        localNotification.region = region
        localNotification.regionTriggersOnce = regionTriggersOnce
        localNotification.alertAction = alertAction
        localNotification.alertBody = alertBody
        localNotification.alertTitle = alertTitle
        localNotification.hasAction = hasAction
        localNotification.applicationIconBadgeNumber = applicationIconBadgeNumber
        localNotification.soundName = soundName
        if let info = localNotification.userInfo {
            localNotification.userInfo = info as [NSObject : AnyObject]
        }
        
        UIApplication.sharedApplication().presentLocalNotificationNow(localNotification)
    }
}
```

## アプリケーションが中断状態の場合の処理

```swift:AppDelegate.swift
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        if let options = launchOptions {
            let notification = options[UIApplicationLaunchOptionsLocalNotificationKey] as! UILocalNotification
            if let region = notification.region {
                print("Received Notification")
            }
        }
```

## アプリケーションがフォアグラウンド状態の場合の処理

```swift:AppDelegate.swift
                print("Received Notification")
            }
        }
        return true
    }

    func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
        if let region = notification.region {
            print("Received Notification")
        }
    }
```

## 参考情報

[Local および Push Notification プログラミングガイド](https://developer.apple.com/jp/documentation/RemoteNotificationsPG.pdf)