swift开发知识收集

Moya+Codable 简单使用

2023-10-09  本文已影响0人  dlxfly

ViewController

import UIKit
import Moya

class ViewController: UIViewController {
     
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        
//        let json = """
//            {
//                "message": "zhangsan",
//                "code": 25
//            }
//            """.data(using: .utf8)!
//        let dataList = try! JSONDecoder().decode(BaseModel.self, from: json)
//        print(dataList.message ?? "")
//        print(dataList.code ?? -1)
//
//    }
        


        let networkProvider = MoyaProvider<NetworkAPI>()
        let target = NetworkAPI.newsList(channelId: "5d8b4d25cf8dfd0001a4143c",listCount: 50)
        networkProvider.request(target) { result in
            print(result)
            switch result {
            case let .success(response): 
                do {
                    let result = try JSONDecoder().decode(BaseModel<NewsBaseModel>.self, from: response.data)
                    print(result.code ?? -1)
                    print(result.data?.channel?.name ?? "")
                    print(result.data?.article_list?.count ?? 0)
                    print(result.data?.article_list?[0].list_title ?? "")

                } catch {
                    print(error)
                }
            case let .failure(error):
                print(error)
            }
        }

    }


}


NewsListRequest.swift


import Foundation
import Moya
 

enum NetworkAPI {
    case newsList(channelId:String,listCount:Int)
}

extension NetworkAPI: TargetType{
    var baseURL: URL {
        return URL(string: "https://app-api.zjol.com.cn")!
    }
    
    var path: String {
        switch self {
        case .newsList:
            return "/api/article/channel_list"
        }
    }
    
    var method: Moya.Method {
        switch self {
        case .newsList:
            return .get
        }
    }
    
    var task: Moya.Task {
        var params: [String: Any] = [:]
//
        switch self {
        case .newsList(let channelId,let listCount):
            params["channel_id"] = channelId
            params["list_count"] = listCount
            params["recommend_switch"] = 0
            return .requestParameters(parameters: params, encoding: URLEncoding.default)
        }
//        return .requestPlain //没有参数的时候不能传 [:]
    }
    
    var headers: [String : String]? {
        var headers: [String: String] = [:]
        headers["Content-type"] = "application/x-www-form-urlencoded"
        headers["X-TIMESTAMP"] = "1696916552221"
        headers["X-SESSION-ID"] = "64a61f1d0531bc0001678bc5"
        headers["X-SIGNATURE"] = "b0b99c243b2888b2c2a674ccb51d3feee33a21405512b2784a8357398dbf1208"
        headers["X-REQUEST-ID"] = "91BAD96D-43E6-4589-81A9-C31A0295CB49"
        return headers
    }
    
}

Model

import Foundation

struct BaseModel<T: Codable>: Codable {
    var code: Int?
    var data: T?
//    var message: String?
}


struct BaseListModel<T: Codable>: Codable {
    var code: Int?
    var data: [T]?
//    var message: String?
}
struct NewsBaseModel: Codable {
    var video_list_play: Bool?
    var tuijian_recommend_switch: Bool?
    var has_more: Bool?
    var channel: channelModel?
    var article_list: [articleListModel]?
}
 
struct channelModel: Codable {
    var mode: Int?
    var channel_ids: [String]?
    var focus_carousel: Bool?
    var name: String?
    var id: String?

}


struct articleListModel: Codable {
    var id: Int?
    var list_title: String?
    var doc_title: String?
  
}

上一篇下一篇

猜你喜欢

热点阅读