Project/Swift+WebView

iOS/WebView/Project - 서버별 테스트 환경 만들기#11

건담아빠 2023. 1. 13. 16:16

 

IOS/Xcode 14X Swift5.7.2 WKWebView 에서 작업 진행

 

이번장에서는 지난 블로그에서 설정한 Constants(상수) 및 AppInfo(싱글톤)를 활용하여

웹뷰에 나타나는 웹서버를 변경할 수 있도록하여 디버깅 및 앱에 대한 테스트 편의성을 높혀보자.

 

앱 실행 환경에 따라 다른 진입 

  • 운영 환경 :  앱 실행 -> 슬플래시 이미지 -> 로컬/개발/스테이징/운영을 선택할 수 있도록 한다.
  • 디버깅 환경 : 앱 실행 -> 슬플래시 이미지 -> 운영 웹뷰 노출

 

작업 진행

먼저 ViewController의 생명주기(Life Cycle) 중 viewDidAppear 함수에 서버를 선택하는 UIAlertController를 설정할 것이다.

https://dchkang83.tistory.com/109

 

IOS/Xcode 14X - View Controller 생명주기 (Life Cycle)

View Controller의 생명주기 (Life-CyCle) 이미지 출처 : https://subscription.packtpub.com/book/application-development/9781783550814/6/ch06lvl1sec60/uiviewcontroller-lifecycle-methods Did는 과거 Will은 미래 이벤트 해석 요약 상세 view

dchkang83.tistory.com

 

BaseViewController를 상속받은 InnitViewController의 ViewDidAppear 부분

BaseViewController를 상속받은 InnitViewController의 ViewDidAppear 부분

 

실행 화면

`스테이징`을 선택하면 싱글톤으로 제작된 AppInfo.swift에 스테이징에 대한 웹서버정보 설정하고 코드에 정의된 콜백함수를 실행한다.

(나중에 콜백함수는 MainController로 이동 후 설정된 웹서버 정보를 뿌려 주겠죠??!)

서버 선택화면

 

InitViewController.swift

UIAlerController를 활용해서 서버를 선택할 수 있도록 하였고, 추후에 웹뷰 설정에 사용될 serverURL은 싱글톤으로 제작된 AppInfo.swift에서 서버정보를 저장한다.

import Foundation
import UIKit

class InitViewController: BaseViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        ...
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        // 메인 컨트롤러로 이동
        let callback = { self.gotoMain() }
        
        if (Utils.isDebug() == true) {
            self.openServerSelectAlert(callback: callback)
        } else {
            DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
                // 딜레이 3초 이후 콜백 함수 호출
                callback()
            }
        }
    }
    
    private func openServerSelectAlert(callback: @escaping() -> Void) {
        let alerts = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        
        alerts.addAction(getAlertAction(serverMode: Constants.SERVER_LOCAL, callback: { callback() }))
        alerts.addAction(getAlertAction(serverMode: Constants.SERVER_DEV, callback: { callback() }))
        alerts.addAction(getAlertAction(serverMode: Constants.SERVER_STG, callback: { callback() }))
        alerts.addAction(getAlertAction(serverMode: Constants.SERVER_PROD, callback: { callback() }))
        alerts.addAction(UIAlertAction(title: "닫기", style: .cancel, handler: { _ in callback() }))
        self.present(alerts, animated: true)
    }
    
    private func getAlertAction(serverMode: String, callback: (() -> Void)? = nil) -> UIAlertAction {
        let title = Constants.SERVERS[serverMode]!["NAME"]!
        
        return UIAlertAction(title: title, style: .default, handler: { _ in
            // 서버 정보 설정
            self.setAppInfo(serverMode: serverMode)
            
            // 콜백
            callback?()
        })
    }
    
    private func setAppInfo(serverMode: String) -> Void {
        let appInfo = AppInfo.shared
        
        appInfo.serverMode = serverMode
        appInfo.serverName = Constants.SERVERS[serverMode]!["NAME"]!
        appInfo.serverUrl = Constants.SERVERS[serverMode]!["URL"]!
    }
    
    private func gotoMain() {
        let appInfo = AppInfo.shared
        Utils.Log("appInfo.serverUrl : \(appInfo.serverUrl)")
        ...
    }
}

 

AppInfo.swift

import Foundation

class AppInfo {
    static let shared = AppInfo() // static을 이용해 Instance를 저장할 프로퍼티를 하나 생성
    private init() {}
 
    ...
    
    // 웹뷰 서버 정보
    var serverMode = Constants.SERVER_PROD
    var serverName = Constants.SERVERS[Constants.SERVER_PROD]!["NAME"]!
    var serverUrl: String = "https://www.google.com"
}

 

Constants.swift

import Foundation

struct Constants {
    static let SERVER_LOCAL: String = "LOCALHOST"
    static let SERVER_DEV: String = "DEVELOPMENT"
    static let SERVER_STG: String = "STAGING"
    static let SERVER_PROD: String = "PRODUCTION"
    
    static let SERVERS = [
        SERVER_LOCAL: [
            "NAME": "로컬",
            "URL": "http://local"
        ],
        SERVER_DEV: [
            "NAME": "개발",
            "URL": "http://dev"
        ],
        SERVER_STG: [
            "NAME": "스테이징",
            "URL": "http://stg"
        ],
        SERVER_PROD: [
            "NAME": "운영",
            "URL": "http://prod"
        ]
    ]
}

 

Uitls.swift

import Foundation

class Utils {
    public static func isDebug() -> Bool {
        #if DEBUG
            return true
        #else
            return false
        #endif
    }
    
    ...
}

 

다음 포스팅에서는 웹뷰 설정부로 넘어가 보자!

 

 

참조

https://stackoverflow.com/questions/35005922/how-do-i-pass-more-parameters-to-a-uialertactions-handler

 

How do I pass more parameters to a UIAlertAction's handler?

Is there any way to pass the array "listINeed" to the handler function "handleConfirmPressed"? I was able to do this by adding it as a class variable but that seemed very hacky and now I want to do...

stackoverflow.com