Swift愛好会アドベントカレンダー最終日です(最終日といいつつ二日も遅れていますm(_ _)m)。
Swift愛好会の1周年に続き、アドベンドカレンダーも埋めることができました。
(ネタを見てると各人好き勝手に楽しんでいて、さすが愛好会らしいアドベントカレンダーだなと思いました^^/)
感謝!
圧倒的感謝です!
感謝の意を表して🍣を流しました。
みんな思う存分🍣を眺めてください!
落ち着け…🍣を数えて落ち着くんだ… pic.twitter.com/ZSdd7LbOFF
— hideyuki nanashima (@jollyjoester) 2016年12月27日
以上!
来年もSwiftで楽しみまくりましょう
本編終わり
おまけ
このアプリは
- タップすると🍣が流れる
- Today Extensionに🍣が流れる
- リッチ通知に🍣が流れる
だけのアプリです。
以前Playgroundで🍣を流す話でPlaygroundに🍣を流しましたが、🍣を流す部分はほぼ同じです。
アプリ本体とそれぞれのExtensionのViewに🍣を流す部分を貼り付けているだけなので、もしそれぞれの実装したことない人はぜひ試しに🍣を流してみましょう
ソースはこちら
https://github.com/jollyjoester/SushiGoRound
タップすると🍣が流れる
🍣流し初級
- UITapGestureRecognizerでタップを検知して
- タップされたら🍣を流す!
簡単です。
応用編としてニコ動みたいに🍣の大きさや流れる速度が変わるようにしてみよう!
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に🍣が流れる
🍣流し中級
- XcodeのFile -> New -> TargetにてToday Extensionを選択。
- Product Nameなどを入力して「Activate "hogehoge" scheme」をActivate。
- TodayViewController.swiftのviewDidLoadで🍣を流す
眺めているだけじゃ飽き足らずタップして🍣を流したくなったらself.extensionContext?.open(url, completionHandler: nil) で自分のURL scheme叩いて本体を起動しよう!
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日悩んだのは内緒・・・メディアアタッチの方のリッチ通知はできたのに😭)
- まずは普通にプッシュ通知を打てるようにしましょう
- 次にXcodeのFile -> New -> TargetにてNotification Content Extensionを選択。
- Product Nameなどを入力して「Activate "hogehoge" scheme」をActivate。
- NotificationViewController.swiftのviewDidLoadで🍣を流す
- Notification Content ExtensionのInfo.plistのNSExtensionAttributesのUNNotificationExtensionCategoryの値をUNNotificationCategoryとしてセット。
- プッシュ通知を送るときのPayloadに下記をセット
- 
categoryにUNNotificationExtensionCategoryと同じ値
- 
mutable-contentに1
 
- 
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) {
        
    }
}
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"
  }
}
以上、他に🍣を流せるところがあったら教えてくれ。
🍣職人におれはなる!
