【Xcode/Swift】某大喜利アプリを真似してみよう [Xib開発]

Storyboard & ライブラリインストール


使用ライブラリ

pod 'SwiftyJSON'
pod 'Alamofire'
pod 'SDWebImage'
pod 'SPIndicator'

各ファイルコード記述

import UIKit
import Alamofire
import SwiftyJSON
import SDWebImage
import Photos
import SPIndicator

class HomeViewController: UIViewController {

    @IBOutlet private weak var odaiTextField: UITextField!
    @IBOutlet private weak var odaiSearchButton: UIButton!
    @IBOutlet private weak var odaiImageView: UIImageView!
    @IBOutlet private weak var odaiCommentView: UITextView!
    @IBOutlet private weak var nextOdaiButton: UIButton!
    @IBOutlet private weak var odaiPostButton: UIButton!

    // 画像カウント用
    private var count = 0
    // ボタンの角丸値
    private let cornerRadius: CGFloat = 12

    override func viewDidLoad() {
        super.viewDidLoad()
        setupView()
    }

    private func setupView() {
        odaiCommentView.layer.cornerRadius = cornerRadius
        nextOdaiButton.layer.cornerRadius = cornerRadius
        odaiPostButton.layer.cornerRadius = cornerRadius
        getImages(keyword: "funny")
    }

    // 画像の取得 (APIを叩いてPixabayからキーワードに該当する画像を持ってくる)
    private func getImages(keyword: String) {
        // Pixabayに登録して個人用のAPIキーを取得する
        let url = "https://pixabay.com/api/?key=<#自分のAPIキー#>&q=\(keyword)"
        AF.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default).responseJSON {
            (response) in
            switch response.result {
            case .success:
                let json: JSON = JSON(response.data as Any)
                guard let imageString = json["hits"][self.count]["webformatURL"].string else {
                    let indicatorView = SPIndicatorView(title: "エラー", message: "画像がありませんでした", preset: .error)
                    indicatorView.present(duration: 1)
                    self.odaiSearchButton.isEnabled = false
                    DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                        self.odaiSearchButton.isEnabled = true
                    }
                    return
                }
                self.odaiImageView.sd_setImage(with: URL(string: imageString), completed: nil)
            case .failure(let error):
                print(error)
            }
        }
    }

    @IBAction func odaiSearchAction(_ sender: Any) {
        self.count = 0
        guard let odaiKeyWord = odaiTextField.text else { return }
        if odaiTextField.text == "" {
            let indicatorView = SPIndicatorView(title: "エラー", message: "検索ワードを入力してください", preset: .error)
            indicatorView.present(duration: 1)
            odaiSearchButton.isEnabled = false
            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                self.odaiSearchButton.isEnabled = true
            }
        } else {
            getImages(keyword: odaiKeyWord)
        }
    }

    @IBAction func searchNextOdaiAction(_ sender: Any) {
        count += 1
        guard let odaiKeyWord = odaiTextField.text else { return }
        if odaiTextField.text == "" {
            getImages(keyword: "funny")
        } else {
            getImages(keyword: odaiKeyWord)
        }
        odaiCommentView.text = ""
    }

    @IBAction func postOdaiAction(_ sender: Any) {
        if odaiCommentView.text == "" {
            let indicatorView = SPIndicatorView(title: "エラー", message: "コメントを入力してください", preset: .error)
            indicatorView.present(duration: 1)
            odaiPostButton.isEnabled = false
            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                self.odaiPostButton.isEnabled = true
            }
            return
        }
        guard let odaiImage = odaiImageView.image else { return }
        let resultViewController = ResultViewController()
        resultViewController.commentString = odaiCommentView.text
        resultViewController.resultImage = odaiImage
        self.navigationController?.pushViewController(resultViewController, animated: true)
    }

}
ひとくちメモ

事前にPixabayというサイトから個人のAPIキーを取得しておきましょう

import UIKit

class ResultViewController: UIViewController {

    @IBOutlet private weak var resultImageView: UIImageView!
    @IBOutlet private weak var resultComment: UILabel!
    @IBOutlet private weak var shareButton: UIButton!
    @IBOutlet private weak var backButton: UIButton!

    var resultImage = UIImage()
    var commentString = String()
    var screenShotImage = UIImage()
    private let cornerRadius: CGFloat = 12

    override func viewDidLoad() {
        super.viewDidLoad()
        setupView()
    }

    private func setupView() {
        shareButton.layer.cornerRadius = cornerRadius
        backButton.layer.cornerRadius = cornerRadius
        resultImageView.image = resultImage
        resultComment.text = commentString
        resultComment.adjustsFontSizeToFitWidth = true
        self.navigationController?.isNavigationBarHidden = true
    }

    // 画像のスクショを取得する
    private func takeScreenShot() {
        let width = CGFloat(UIScreen.main.bounds.size.width)
        let height = CGFloat(UIScreen.main.bounds.size.height / 1.3)
        let size = CGSize(width: width, height: height)
        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
        self.view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
        if let image = UIGraphicsGetImageFromCurrentImageContext() {
            screenShotImage = image
        }
        UIGraphicsEndImageContext()
    }

    @IBAction func shareAction(_ sender: Any) {
        takeScreenShot()
        let items = [screenShotImage] as [Any]
        let activityViewController = UIActivityViewController(activityItems: items, applicationActivities: nil)
        present(activityViewController, animated: true, completion: nil)
    }

    @IBAction func backAction(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }

}
import UIKit

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        guard let _ = (scene as? UIWindowScene) else { return }
        // 追記 -----ここから (NavigationControllerを使用する場合)
        window = UIWindow(windowScene: scene as! UIWindowScene)
        window?.makeKeyAndVisible()
        let homeViewController = HomeViewController()
        let rootViewController = UINavigationController(rootViewController: homeViewController)
        window?.rootViewController = rootViewController
        // 追記 -----ここまで
    }

    func sceneDidDisconnect(_ scene: UIScene) {

    }

    func sceneDidBecomeActive(_ scene: UIScene) {

    }

    func sceneWillResignActive(_ scene: UIScene) {

    }

    func sceneWillEnterForeground(_ scene: UIScene) {

    }

    func sceneDidEnterBackground(_ scene: UIScene) {

    }

}

まとめ

今回は以上です、これからはもっと詳細を追って解説する記事を書けるように頑張ります、、、(サボり癖が治らん)

◉今日の格言

ー Winston Churchill

WInston
WInston

The pessimist sees difficulty in every opportunity. The optimist sees opportunity in every difficulty.

(悲観主義者は全ての機会に困難を見出し、楽観主義者は全ての困難に機会を見出す。)