0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Swift】アプリ開発をする際に便利だった自作メソッド

Posted at

はじめに

最近ようやくExtensionの使い方がわかってきたので、自分の脳内整理も含めてこの記事を書きます。
あと、この記事は初心者による初心者のための記事なので、ある程度Swiftできるよって人にとって有用な情報はほぼないと思います。

エラーを知らせるアラート

extension UIViewController{
    func showErrorAlert(title: String, message: String, actionTitle: String){
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let okAction = UIAlertAction(title: actionTitle, style: .default) { action in
            alert.dismiss(animated: true)
        }
        alert.addAction(okAction)
        self.present(alert, animated: true)
    }

エラーのタイトル、メッセージ、アクションボタンのタイトルを入れてあげればすぐにエラーの表示を行えます。実際のユーザーに使ってもらう時ってよりも、テストユーザーにテストしてもらうときにどこでエラーが起きたのかテストユーザーにも伝えやすいって点で便利でした。

ActivityIndicatorを表示する

extension UIView{

    func showIndicator(color: UIColor) -> UIActivityIndicatorView{
        var activityIndicator: UIActivityIndicatorView!
        activityIndicator = UIActivityIndicatorView()
        activityIndicator.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
        activityIndicator.hidesWhenStopped = true
        activityIndicator.style = .large
        activityIndicator.color = color
        self.addSubview(activityIndicator)
        activityIndicator.startAnimating()
        
        return activityIndicator
    }
}

UIActivityIndicatorはロード中とかを表すクルクルするアレです。以下みたいに使用してました。

ViewContorller
import UIKit
import Firebase

class ViewController: UIViewController{
    @IBOutlet var label: UILabel!

    @override func viewDidLoad{
        super.viewDidLoad()
        
        //labelに文字が表示されるまでIndicatorを表示させる
        let activityIndicator = label.showIndicator(color: .white)

        let db = Firestore.firestore()
        db.collection("Memo").whereField("title", isEqualTo: "sport").getDocuments{ memoSnaps, error in
            if error != nil{
                print(error)
                //Indicatorを止める
                activityIndicator.stopAnimating()
            }else{
                memoSnaps.documents.forEach{memoSnap in
                    let memoDic = memoSnap.data()
                    let memoData = Memo(dic: memoDic)
                    self.label.text = memoData.memo
                }
                //Indicatorを止める
                activityIndicator.stopAnimating()
            }
        }
    }
}

Firebaseでデータをロードしている間はクルクルを表示させるようにしています。自動で止める方法はわからなかったので、止める時だけ手動で止めてます。

URLから画像を表示する

import UIKit
import KingFisher

extension UIImageView{
    func setImageFromURL(url: String){
        //上記のshowIndicator
        let avtivityIndicator = self.showIndicator
        
        if url == ""{
            activityIndicator.stopAnimating()
            self.image = UIImage(systemName: "person")
        }else{
            let url = URL(string: url)
            KingfisherManager.shared.downloader.downloadImage(with: url!){result in
                switch result{
                case .success(let value):
                    activityIndicator.stopAnimating()
                    self.image = value.image
                case .failure(let error):
                    print(error)
                    print("画像の読み込みに失敗しました")
                    activityIndicator.stopAnimating()
                    self.image = UIImage(systemName: "person")
                }
            }
        }
    }
}

URLから画像データを読み込むのにはKingFisherを使用しています。
上記のActivityIndicatorと組み合わせて、画像データをロードしている間はクルクルを表示し、画像が表示できたらクルクルを止めるようにしています。

@IBOutlet var imageView: UIImageView!

imageView.setImageFromUrl(url: "https://misoshiru.oishii")

みたいな感じで使用してました。

終わりに

いろんなメソッドを自分の作るプロダクトに合わせて作ってると思いますが、上記のメソッドは大抵のアプリでは有用なんじゃないかなと思います。
こう書けばもっと良くなるとか、こんなメソッドもあるとか、間違ってる箇所あるとかありましたら是非教えてください。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?