behan의 개인적인 기술 블로그

Swift) Alamofire Router, Combine 사용 본문

iOS/Swift

Swift) Alamofire Router, Combine 사용

behan 2022. 2. 2. 19:30

Router 설정

let BASE_URL = "베이스 URL"
let SERVICE_KEY = "서비스키"
enum Router: URLRequestConvertible {

    case getCandidateInfo(serviceKey: String = SERVICE_KEY!,
                          pageNo: Int = 1,
                          numOfRows: Int = 10,
                          sgId: String,
                          sgTypecode: String,
                          resultType: String = "json",
                          sggName: String = "",
                          sdName: String = "")
    case getWinnerInfo(serviceKey: String = SERVICE_KEY!,
                       pageNo: Int = 1,
                       numOfRows: Int = 10,
                       sgId: String,
                       sgTypecode: String,
                       resultType: String = "json",
                       sggName: String = "",
                       sdName: String = "")
    
    case getPledge(serviceKey: String = SERVICE_KEY!,
                   pageNo: Int = 1,
                   numOfRows: Int = 10,
                   sgId: String,
                   sgTypecode: String,
                   resultType: String = "json",
                   cnddtId: String)
    
    var baseURL: URL {
        return URL(string: BASE_URL)!
    }
    
    var endPoint: String {
        switch self {
        case .getCandidateInfo:
            return "PofelcddInfoInqireService/getPofelcddRegistSttusInfoInqire"
        case .getWinnerInfo:
            return "WinnerInfoInqireService2/getWinnerInfoInqire"
        case .getPledge:
            return "ElecPrmsInfoInqireService/getCnddtElecPrmsInfoInqire"
        }
    }
    
    var method: HTTPMethod {
        switch self {
        case .getCandidateInfo: return .get
        case .getWinnerInfo: return .get
        case .getPledge: return .get
        }
    }
    
    var parameters: Parameters {
        switch self {
        case let .getCandidateInfo(serviceKey, pageNo, numOfRows, sgId, sgTypecode, resultType, sggName, sdName):
            var params = Parameters()
            params["serviceKey"] = serviceKey
            params["pageNo"] = pageNo
            params["numOfRows"] = numOfRows
            params["sgId"] = sgId
            params["sgTypecode"] = sgTypecode
            params["resultType"] = resultType
            params["sggName"] = sggName
            params["sdName"] = sdName
            return params
            
        case let .getWinnerInfo(serviceKey, pageNo, numOfRows, sgId, sgTypecode, resultType, sggName, sdName):
            var params = Parameters()
            params["serviceKey"] = serviceKey
            params["pageNo"] = pageNo
            params["numOfRows"] = numOfRows
            params["sgId"] = sgId
            params["sgTypecode"] = sgTypecode
            params["resultType"] = resultType
            params["sggName"] = sggName
            params["sdName"] = sdName
            return params
            
        case let .getPledge(serviceKey, pageNo, numOfRows, sgId, sgTypecode, resultType, cnddtId):
            var params = Parameters()
            params["serviceKey"] = serviceKey
            params["pageNo"] = pageNo
            params["numOfRows"] = numOfRows
            params["sgId"] = sgId
            params["sgTypecode"] = sgTypecode
            params["resultType"] = resultType
            params["cnddtId"] = cnddtId
            return params
        }
    }
    
    func asURLRequest() throws -> URLRequest {
        let url = baseURL.appendingPathComponent(endPoint)
        var request = URLRequest(url: url)
        request.method = method
        
        switch self {
        case .getCandidateInfo:
            request = try URLEncoding.default.encode(request, with: parameters)
        case  .getWinnerInfo:
            request = try URLEncoding.default.encode(request, with: parameters)
        case .getPledge:
            request = try URLEncoding.default.encode(request, with: parameters)
        }
        
        return request
    }
}

Combine 사용

    func getPledge(_ election: Election, _ commonCode: CommonCode, _ info: CandidateItem) {
        isLoading = true
        AF.request(Router.getPledge(sgId: commonCode.sgId, sgTypecode: election.rawValue, cnddtId: info.cnddtId))
            .publishDecodable(type: PledgeResponse.self)
            .compactMap { $0.value }
            .sink { [weak self] completion in
                guard let self = self else { return }
                guard let pleInfo = self.pledgeInfo else {
                    self.isLoading = false
                    print ("pleInfo fail")
                    self.saveRecentSearchCandidate(OverallData(election: election, commonCode: commonCode, candidateItem: info, posterImage: info.posterImage, elected: info.elected, pledgeArray: self.pledges))
                    return }
                self.pledgeSplit(pleInfo)
                self.saveRecentSearchCandidate(OverallData(election: election, commonCode: commonCode, candidateItem: info, posterImage: info.posterImage, elected: info.elected, pledgeArray: self.pledges))
                self.isLoading = false
            } receiveValue: { [weak self] receiveValue in
                guard let self = self else { return }
                self.pledgeInfo = receiveValue.getResponse
            }
            .store(in: &subscription)

    }