LoginSignup
35
11

More than 5 years have passed since last update.

続:いろんなところでsushiを流す話

Last updated at Posted at 2016-12-27

Swift愛好会アドベントカレンダー最終日です(最終日といいつつ二日も遅れていますm(_ _)m)。

Swift愛好会の1周年に続き、アドベンドカレンダーも埋めることができました。
(ネタを見てると各人好き勝手に楽しんでいて、さすが愛好会らしいアドベントカレンダーだなと思いました^^/)

感謝!
圧倒的感謝です!

感謝の意を表して🍣を流しました。
みんな思う存分🍣を眺めてください!

以上!
来年もSwiftで楽しみまくりましょう:tada:

本編終わり

おまけ

このアプリは

  • タップすると🍣が流れる
  • Today Extensionに🍣が流れる
  • リッチ通知に🍣が流れる

だけのアプリです。

以前Playgroundで🍣を流す話でPlaygroundに🍣を流しましたが、🍣を流す部分はほぼ同じです。

アプリ本体とそれぞれのExtensionのViewに🍣を流す部分を貼り付けているだけなので、もしそれぞれの実装したことない人はぜひ試しに🍣を流してみましょう:smile:

ソースはこちら
https://github.com/jollyjoester/SushiGoRound

タップすると🍣が流れる

🍣流し初級

  1. UITapGestureRecognizerでタップを検知して
  2. タップされたら🍣を流す!

簡単です。
応用編としてニコ動みたいに🍣の大きさや流れる速度が変わるようにしてみよう!

ViewController.swift
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapped(_:)))
        self.view.addGestureRecognizer(tapGestureRecognizer)

    }

    func tapped(_ sender: UITapGestureRecognizer) {

        let screenWidth = UIScreen.main.bounds.size.width
        let screenHeight = UIScreen.main.bounds.size.height
        let rand = CGFloat(arc4random_uniform(100)) / 100

        let sushi = UILabel(frame: CGRect(x: screenWidth, y: screenHeight * rand, width: 44, height: 44))
        sushi.font = UIFont(name: "HelveticaNeue", size: 36)
        sushi.text = "🍣"
        view.addSubview(sushi)

        UIView.animate(withDuration: 3, delay: 0, options: [.curveLinear], animations: { () -> Void in
            sushi.center = CGPoint(x: -sushi.bounds.size.width / 2, y: sushi.center.y)
        }, completion: { (Bool) -> Void in
            sushi.removeFromSuperview()
        })
    }
}

Today Extensionに🍣が流れる

🍣流し中級

  1. XcodeのFile -> New -> TargetにてToday Extensionを選択。
  2. Product Nameなどを入力して「Activate "hogehoge" scheme」をActivate。
  3. TodayViewController.swiftのviewDidLoadで🍣を流す

眺めているだけじゃ飽き足らずタップして🍣を流したくなったらself.extensionContext?.open(url, completionHandler: nil) で自分のURL scheme叩いて本体を起動しよう!

TodayViewController.swift
import UIKit
import NotificationCenter

class TodayViewController: UIViewController, NCWidgetProviding {

    override func viewDidLoad() {
        super.viewDidLoad()

        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(TodayViewController.tapped(_:)))
        self.view.addGestureRecognizer(tapGestureRecognizer)

        (0...2).forEach {
            let sushi = UILabel(frame: CGRect(x: view.bounds.size.width, y: 33, width: 44, height: 44))
            sushi.text = "🍣"
            view.addSubview(sushi)

            UIView.animate(withDuration: 3, delay: TimeInterval($0), options: [.curveLinear, .repeat], animations: { () -> Void in
                sushi.center = CGPoint(x: 0, y: sushi.center.y)
            }, completion: nil)
        }
    }

    func tapped(_  sender: UITapGestureRecognizer) {
        let url = URL(string: "sushigoround://")!
        self.extensionContext?.open(url, completionHandler: nil)
    }
}

リッチ通知に🍣が流れる

🍣流し上級

iOS10からはリッチ通知のカスタムUIでプッシュ通知にも🍣が流せる!
(ちなみにiPhone5SではiOS10であっても無理なようで2日悩んだのは内緒・・・メディアアタッチの方のリッチ通知はできたのに😭)

  1. まずは普通にプッシュ通知を打てるようにしましょう
  2. 次にXcodeのFile -> New -> TargetにてNotification Content Extensionを選択。
  3. Product Nameなどを入力して「Activate "hogehoge" scheme」をActivate。
  4. NotificationViewController.swiftのviewDidLoadで🍣を流す
  5. Notification Content ExtensionのInfo.plistのNSExtensionAttributesUNNotificationExtensionCategoryの値をUNNotificationCategoryとしてセット。
  6. プッシュ通知を送るときのPayloadに下記をセット
    • categoryUNNotificationExtensionCategoryと同じ値
    • mutable-contentに1
NotificationViewController.swift
import UIKit
import UserNotifications
import UserNotificationsUI

class NotificationViewController: UIViewController, UNNotificationContentExtension {

    override func viewDidLoad() {
        super.viewDidLoad()

        (0...2).forEach {
            let sushi = UILabel(frame: CGRect(x: view.bounds.size.width, y: 33, width: 44, height: 44))
            sushi.text = "🍣"
            view.addSubview(sushi)

            UIView.animate(withDuration: 3, delay: TimeInterval($0), options: [.curveLinear, .repeat], animations: { () -> Void in
                sushi.center = CGPoint(x: 0, y: sushi.center.y)    
            }, completion: nil)
        }

    }

    func didReceive(_ notification: UNNotification) {

    }
}
AppDelegate.swift
import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        if #available (iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()

            let category = UNNotificationCategory(identifier: "myNotificationCategory", actions: [], intentIdentifiers: [], options: []) // ここのidentifierをセット
            center.setNotificationCategories([category])

            center.requestAuthorization(options: [.sound, .alert, .badge], completionHandler: {
                (granted, error) in
                if granted {
                    application.registerForRemoteNotifications()
                } else {
                    print("Don't allow to send push notification")
                }
            })
        }

        return true
    }
{
  "aps": {
    "alert": "落ち着つけ・・・\n『sushi』を数えて落ち着くんだ・・・",
    "mutable-content": 1,
    "category": "myNotificationCategory"
  }
}

以上、他に🍣を流せるところがあったら教えてくれ。
🍣職人におれはなる!

35
11
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
35
11