Sponsored Link
どうも3urpriseのヤマサキです。
iOS8.xから通知の形式?が増えたので基礎的なUILocalNotificationの動作を見てみましょう
まずはこれ、ユーザーに通知の許可をもらわないと通知できないのでそこから
適当にボタン二つ配置したViewを作成してもらって
import UIKit
class ViewController: UIViewController, UIAlertViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// 通知許可をアラート表示にて
UIApplication.sharedApplication().registerUserNotificationSettings(
UIUserNotificationSettings(
forTypes:UIUserNotificationType.Sound | UIUserNotificationType.Alert,
categories: nil)
)
}
// 通知
@IBAction func _nowNotification(sender: AnyObject) {
// Notificationの生成する.
let myNotification: UILocalNotification = UILocalNotification()
// メッセージを代入する
myNotification.alertBody = "通知(即)"
// Timezoneを設定をする
myNotification.timeZone = NSTimeZone.defaultTimeZone()
// Notificationを表示する
UIApplication.sharedApplication().scheduleLocalNotification(myNotification)
}
// 10秒後発火
@IBAction func _10secNotification(sender: AnyObject) {
// Notificationの生成する
let myNotification: UILocalNotification = UILocalNotification()
// メッセージを代入する
myNotification.alertBody = "通知(10秒後)"
// 再生サウンドを設定する
myNotification.soundName = UILocalNotificationDefaultSoundName
// Timezoneを設定する
myNotification.timeZone = NSTimeZone.defaultTimeZone()
// 10秒後に設定する
myNotification.fireDate = NSDate(timeIntervalSinceNow: 10)
// Notificationを表示する
UIApplication.sharedApplication().scheduleLocalNotification(myNotification)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
通知許可をアラートで表示
これで許可を求められるので許可にすると通知が有効になります。
続いてボタンを押した時の動作を作ります。
今回はボタンを押したら即通知が出るパターンと10秒の時間差を置いて通知される2つのパターンを作りました。
コメント見てもらえばわかると思いますが簡単です。
そしてこれだけじゃアプリがフォアグラウンド(起動状態)だと通知がされないのでAppDelegateの方に追記していきます。
// 起動中に通知を受信した時とバックグラウンドから復帰した時の動作
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
// アプリ起動中(フォアグラウンド)に通知が届いた場合
if (application.applicationState == UIApplicationState.Active) {
var alert = UIAlertView()
alert.title = "アラートのタイトル"
alert.message = "アラートの本文"
notification.alertAction = "OK"
alert.addButtonWithTitle(notification.alertAction!)
alert.show()
println("アプリ起動中(フォアグラウンド)に通知が届いた場合")
// アプリがバックグラウンドから復帰した場合
} else if (application.applicationState == UIApplicationState.Inactive) {
println("アプリがバックグラウンドから復帰した場合")
}
}
didReceiveLocalNotificationをappDelegateに追記します。
これで通知の動作はOKです
環境は xcode6.x で iOS8.1
今度は通知のボタンがカスタムできるみたいなのでそれできたらまた載せます
Sponsored Link
ツイート
SwiftにてUILocalNotificationを動作させる方法
