FaceID認証とLottieアニメーション

機能説明
- FaceID認証をクリアしたら、画面遷移先でLottieアニメーションを再生
Info.plist
-
Privacy - Face ID Usage Description
を追加します
コード
- Podfileには、
pod 'lottie-ios'
を入力
Podfile
pod 'lottie-ios'
ViewController(FaceID実装)
-
import LocalAuthentication
を入力 - 使用しているiOSデバイスがFaceID認証(顔認証)に対応しているかを
LAContext
Classを使用して調べます - FaceIDに対応しているか調べる為に、
LAContext
が持っているcanEvaluatePolicy()
メソッドを使用します
ViewController
import UIKit
import LocalAuthentication
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func faceID(_ sender: Any) {
let context = LAContext()
var error: NSError? = nil
if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
let reason = "touch id!"
context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { [self] success, error in
DispatchQueue.main.async { [self] in
guard success, error == nil else{
//認証失敗時
self.alert(titleString: "!!!Faild!!!", messageString: "FaceID認証に失敗しました")
return
}
//認証成功時
self.alert(titleString: "!!!Succesd!!!", messageString: "FaceID認証に成功しました")
}
}
}
}
func alert(titleString:String,messageString:String){
let alert = UIAlertController(title: titleString, message: messageString, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in
let LottieVC = self.storyboard?.instantiateViewController(identifier: "LottieVC") as! LottieViewController
self.navigationController?.pushViewController(LottieVC, animated: true)
}))
present(alert, animated: true, completion: nil)
}
}
LottieViewController(Lottieアニメーションを実装)
-
import Lottie
を入力 -
AnimationView
classのインスタンスを作成 -
animationView.frame = CGRect(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat)
でアニメーションを表示させる範囲を作成 -
animationView.animation = 表示したいアニメーションデータ
は表示したいアニメーションデータを設定 -
animationView.loopMode = .loop
は繰り返し再生されるように設定 -
animationView.play()
で再生 -
animationView.stop()
でアニメーションを停止
LottieViewController
import UIKit
import Lottie
class LottieViewController: UIViewController {
let animationView = AnimationView()
let lottieAnimation = Animation.named("Lottieアニメーションのデータ")
override func viewDidLoad() {
super.viewDidLoad()
createLottie()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.isNavigationBarHidden = true
}
func createLottie(){
animationView.frame = CGRect(x: 0, y: 88, width: 442, height: 412)
animationView.animation = lottieAnimation
animationView.contentMode = .scaleToFill
animationView.loopMode = .loop
animationView.play()
view.addSubview(animationView)
}
@IBAction func back(_ sender: Any) {
animationView.removeFromSuperview()
animationView.stop() //アニメーションをストップ
let VC = self.storyboard?.instantiateViewController(identifier: "VC") as! ViewController
self.navigationController?.pushViewController(VC, animated: true)
}
}
終わり
結構簡単にアニメーションが出来て楽しいです。
ご指摘などがありましたら、コメントまでお願いします。