티스토리 뷰

iOS/Open Library

iOS) Moya 사용

hyun99999 2021. 7. 22. 11:28
728x90
반응형

Moya

BandAPI

import Foundation
import Moya

class BandAPI {
    static let shared = BandAPI()
    static let provider = MoyaProvider<BandService>()

    func getBands(completion: @escaping ([Band]) -> ()) {
        BandAPI.provider.request(.bands) { response in
            switch response {
            case .success(let result):
                do {
                    let results = try JSONDecoder().decode(BandlistDataModel.self, from: result.data)
                    completion(results.band)
                    print(results.message)
                } catch let err {
                    print("JSONDecode: \(err.localizedDescription)")
                    debugPrint(err)
                }
            case .failure(let err):
                print(".failure: \(err.localizedDescription)")
            }
        }
    }
}

BandService

import Foundation
import Moya

public enum BandService {
    case bands
}

extension BandService: TargetType {
    public var baseURL: URL {
        return URL(string: GeneralAPI.baseURL)!
    }

    public var path: String {
        switch self {
        case .bands:
            return "/api/bands"
        }
    }

    public var method: Moya.Method {
        return .get
    }

    public var sampleData: Data {
        return  "sampleData".data(using: .utf8)!
    }

    public var task: Task {
        .requestPlain
    }

    public var headers: [String : String]? {
        switch self {
        default:
            return ["Content-Type": "application/json"]
        }
    }
}

model

// MARK: - BandlistDataModel
struct BandlistDataModel: Codable {
    let band: [Band]
    let message: String
}

// MARK: - Band
struct Band: Codable {
    let id: String
    let category: Category
    let bandDescription: String
    let img: String
    let member: Int
    let name, owner: String

    enum CodingKeys: String, CodingKey {
        case id = "_id"
        case category
        case bandDescription = "description"
        case img, member, name, owner
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        id = (try? values.decode(String.self, forKey: .id)) ?? ""
        category = (try? values.decode(Category.self, forKey: .category)) ?? Category(id: "", name: "")
        bandDescription = (try? values.decode(String.self, forKey: .bandDescription)) ?? ""
        img = (try? values.decode(String.self, forKey: .img)) ?? ""
        member = (try? values.decode(Int.self, forKey: .member)) ?? 0
        name = (try? values.decode(String.self, forKey: .name)) ?? ""
        owner = (try? values.decode(String.self, forKey: .owner)) ?? ""
    }
}

// MARK: - Category
struct Category: Codable {
    let id, name: String

    enum CodingKeys: String, CodingKey {
        case id = "_id"
        case name
    }
}

main

private var bandList = [Band]()
...
BandAPI.shared.getBands { response in
    self.bandList = response
}
728x90
반응형
댓글
최근에 올라온 글
최근에 달린 댓글
글 보관함
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
링크
Total
Today
Yesterday