LoginSignup
94
95

More than 5 years have passed since last update.

[iOS8以降]Push通知の実装とテスト(swift)

Last updated at Posted at 2015-09-02

概要

  1. SwiftでPush通知受信処理を実装する
  2. houstonを使って、Push通知を送信する

参考記事

SwiftでPush通知受信処理を実装する

AppDelegate.swift

AppDelegate.swift
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    // バッジ、サウンド、アラートをリモート通知対象として登録する
    let settings = UIUserNotificationSettings(forTypes: [.Badge, .Sound, .Alert], categories: nil)
    UIApplication.sharedApplication().registerForRemoteNotifications()
    UIApplication.sharedApplication().registerUserNotificationSettings(settings)

    if let userInfo = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] {
      // アプリが起動していない時にpush通知が届き、push通知から起動した場合
    }
  }

  // Push通知の登録が完了した場合、deviceTokenが返される
  func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData ) {
    print("deviceToken: \(deviceToken.description)")
  }

  // Push通知が利用不可であればerrorが返ってくる
  func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
    NSLog("error: " + "\(error)")
  }

  // Push通知受信時とPush通知をタッチして起動したときに呼ばれる
  func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    switch application.applicationState {
    case .Inactive:
      // アプリがバックグラウンドにいる状態で、Push通知から起動したとき
      break
    case .Active:
      // アプリ起動時にPush通知を受信したとき
      break
    case .Background:
      // アプリがバックグラウンドにいる状態でPush通知を受信したとき
      break
    }
  }
}

RubyでPush通知を送信する

houstonというRubyのライブラリを使って、Push通知を送信します

Gemのインストール

$ gem install rake
$ gem install houston

Rakefileを作成して、push通知用のタスクを作成

server_certificates_sandbox.pemはiOSでプッシュ通知を実装する方法の超詳細まとめ(前編)で作成したものです。

# Rakefile:

require 'houston'

ROOT = File.expand_path(File.dirname(__FILE__))

task :push_notification do
  # Environment variables are automatically read, or can be overridden by any specified options. You can also
  # conveniently use `Houston::Client.development` or `Houston::Client.production`.
  APN = Houston::Client.development
  APN.certificate = File.read("#{ROOT}/pem/server_certificates_sandbox.pem")
  # An example of the token sent back when a device registers for notifications
  # token = "<ce8be627 2e43e855 16033e24 b4c28922 0eeda487 9c477160 b2545e95 xxxxxxx>"
  token = ENV['DEVICE_TOKEN']

  # Create a notification that alerts a message to the user, plays a sound, and sets the badge on the app
  notification = Houston::Notification.new(device: token)
  notification.alert = "Hello, World!"

  # Notifications can also change the badge count, have a custom sound, have a category identifier, indicate available Newsstand content, or pass along arbitrary data.
  notification.badge = 57
  notification.sound = "sosumi.aiff"
  notification.category = "INVITE_CATEGORY"
  notification.content_available = true
  notification.custom_data = {foo: "bar"}

  # And... sent! That's all it takes.
  APN.push(notification)
end

実行

$ DEVICE_TOKEN=<xxxx> rake push_notification

iPhoneに通知が届けば成功です

94
95
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
94
95