Category Archives: Swift

Watch Push通知

Rails

Houston設定

http://mycoderepository.org/?p=1847

task :push_notifications 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 = Houston::Client.production
  APN.certificate = File.read("config/pem/production_com.mycompany.do-lists.pem")
  # APN.certificate = File.read("config/pem/development_mycompany.push-test2.pem")
  # An example of the token sent back when a device registers for notifications
  token = "<{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 = "Have you had a sandwich yet?"

  # 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 = 1
  notification.sound = "sosumi.aiff"
  notification.category = "RECORD_CATEGORY"
  notification.content_available = true
  notification.custom_data = {foo: "bar"}

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


Swift

Watch > Interface.storyboard

Category Nameを設定
Screen Shot 2016-03-13 at 11.42.26 AM

AppDelegate.swift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var list: List?


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


        // プッシュ通知登録
        UIApplication.sharedApplication().registerForRemoteNotifications()

        // 通知設定
        let action1 = UIMutableUserNotificationAction()
        action1.title = "YES"
        action1.identifier = "id1"
        action1.activationMode = UIUserNotificationActivationMode.Background

        let action2 = UIMutableUserNotificationAction()
        action2.title = "NO"
        action2.identifier = "id2"
        action2.activationMode = UIUserNotificationActivationMode.Background

        // 通知カテゴリ設定作成
        let recordCategory = UIMutableUserNotificationCategory()
        recordCategory.identifier = "RECORD_CATEGORY"
        recordCategory.setActions([action1, action2], forContext: .Default)

        let categories: Set<NSObject> = [recordCategory]

        // バッジ、サウンド、アラートをリモート通知対象として登録する
        let settings = UIUserNotificationSettings(forTypes: .Alert, categories: categories as? Set<UIUserNotificationCategory>)


        UIApplication.sharedApplication().registerUserNotificationSettings(settings)

        return true
    }

    // 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)")
    }

    func application(application: UIApplication,
        handleActionWithIdentifier identifier: String?,
        forRemoteNotification userInfo: [NSObject : AnyObject],
        withResponseInfo responseInfo: [NSObject : AnyObject], // 追加
        completionHandler: (() -> Void)) {
            print("push touched ")
            print(userInfo)

            if identifier == "id1" {
                // list読み込み
                let list = List()
                list.id = "62"

                let record = Record()

                // 日付取得
                let now = NSDate()
                let dateFormatter = NSDateFormatter()
                dateFormatter.dateFormat = "YYYYMMdd"
                let date = dateFormatter.stringFromDate(now)

                record.date = date
                list.record = record
                list.postRecord()
            }


            if(identifier == "id2") {
                print("pushed id2")

            }

            // 終了時に呼ばれなければならない
            completionHandler()
    }
}

watch extension > interfaceController.swift

override func handleActionWithIdentifier(identifier: String?, forRemoteNotification remoteNotification: [NSObject : AnyObject]){

        if identifier == "id1" {
            // list読み込み
            let list = List()
            list.id = "62"

            let record = Record()

            // 日付取得
            let now = NSDate()
            let dateFormatter = NSDateFormatter()
            dateFormatter.dateFormat = "YYYYMMdd"
            let date = dateFormatter.stringFromDate(now)

            record.date = date
            list.record = record
            list.postRecord()
        }
    }

NSTimer

引数なし

override func viewDidLoad() {
    super.viewDidLoad()

    // タイマー生成
    let timer = NSTimer(timeInterval: 1.0, target: self, selector: "timerAction", userInfo: nil, repeats: true)

    // 登録
    NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)


}

// タイマーで実行するアクション
func timerAction() {
    print("timer!")
}

引数あり

class ViewController: UIViewController {
    var count:Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        // タイマー生成
        let timer = NSTimer(timeInterval: 1.0, target: self, selector: "timerAction:", userInfo: nil, repeats: true)

        // 登録
        NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)


    }

    // タイマーで実行するアクション
    func timerAction(timer: NSTimer) {
        count += 1
        if count == 10 {
            // timerを停止する
            timer.invalidate()
        }
        print(self.count)
    }
}


Dictionary配列

// 配列生成
var scores = Array<Dictionary<String,Int>>()

// 要素生成
var score = Dictionary<String,Int>()
score["note"] = 1
scores.append(score)

// 要素の取得
print(scores[0]["note"]!)

class オプショナル変数でのイニシャライズ

class Human {
    let name:String
    // ageをオプショナル型に
    var age:Int?

    // ageの初期値をnilに
    init(name:String, age:Int?=nil) {
        self.name = name
        self.age = age
    }
}

let human1 = Human(name: "yohei", age:35)
// ageを省略できる
let human2 = Human(name: "yohei")

// 戻り値は35(オプショナル型)
print(human1.age)

// 戻り値はnil
print(human2.age)

Segueの遷移先にプロパティを渡す(分岐)

以下のように、

segue.identifierで、移行先のsegueを確認できる。

// 遷移先にプロパティを渡す
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        switch segue.identifier! {
        case "toPlayRecordView":

            // 移行先のviewControllerを取得
            let destinationNavigationController = segue.destinationViewController as! UINavigationController
            let recordViewController = destinationNavigationController.topViewController as! PlayRecordViewController

            // プロパティの設定
            recordViewController.record = song.records![0]

        case "toCreateRecordView":

            // 移行先のviewControllerを取得
            let destinationNavigationController = segue.destinationViewController as! UINavigationController
            let createRecordViewController = destinationNavigationController.topViewController as! CreateRecordViewController

            // プロパティの設定
            createRecordViewController.record = song.records![0]

        default:
            break
        }
    }

classをiOS,WatchOS間で共有

手順

  1. 該当するclassを選択
  2. File Inspector > Target Membership > Watch Extensionを選択

注意

共有クラスの中で、WatchKitで使用できないライブラリが含まれているとエラーがでる

itune connect

Xcode

  1. アプリバージョン、ビルドバージョン設定
    Generalから設定

  2. シュミレーターをデバイスに設定

  3. アーカイブ
    Product > Archive

  4. validateをクリック

  5. アップロード

itunes connect

  1. 上記でアップロードしたビルドファイル選択
  2. submit for review をクリック

Navigation Bar 高さ取得

結果がオプショナル型になるので注意

// ステータスバーの高さを取得
let statusBarHeight: CGFloat = UIApplication.sharedApplication().statusBarFrame.height

// ナビゲーションバーの高さを取得
let navBarHeight = self.navigationController?.navigationBar.frame.size.height