This is the 17th day of my participation in the Gwen Challenge.More article challenges

Some simple summaries:

Some space has been devoted to the following points:

  • As project requirements begin, iOS development should be prepared in advance.

  • Some basic library usages are introduced: R. swift, SnapKit, Alamofire, Moya.

  • I shared my own experiences with JSON parsing: moving directly from OC to ObjectMapper, and finally using the native Codable protocol.

  • Interspersed Swift and JS interactions, and Flutter and JS interactions.

If not interspersed with JS interaction, I have made some paving and explanation of App resource management, UI layout and network request. Although interaction with JS is not used in this App writing, it will always be used in some places.

In fact, I wrote this project using RxSwift, which is also a beginner to RxSwift. I will learn while writing, so I will explore this part while writing App, so if there is anything wrong or bad, please give me advice.

Ok, now that so much ink has been spent, let’s begin today’s topic – the network request module writing.

Network request module before the preparation of matters needing attention

Since the App we wrote this time is the development API of other websites, there are very good interface documents on the website:

Play with the Android open API

As an App developer, start writing a network request module

  • Read through the interface documentation sent to you at the back end.

  • Know how each interface requests, get or POST or whatever.

  • JSON format observation, through observation, can be summarized to find the rule, write with generics BaseModel, at the same time flexible reuse.

  • If you can, you can do simple debugging with a tool like Postman.

Android project related interface example:

There are a lot of android interfaces. Due to the limited space and similarity of interfaces, I only analyze and code the two interfaces of the project here.

project

  • Project classification
Methods: https://www.wanandroid.com/project/tree/json GET parameters: noCopy the code

JSON sample:

{" data ": [{" children" : [], "courseId" : 13, "id", 294, "name" : "complete projects", "order" : 145000, "parentChapterId" : 293, "userControlSetTop":false, "visible":0 }, ], "errorCode":0, "errorMsg":"" }Copy the code
  • Item list data
Methods: https://www.wanandroid.com/project/list/1/json?cid=294 GET parameters: the id of the cid classification, the classification in the interface to obtain the data of a single element in the array of the id page: joining together in the link, starting from 1.Copy the code

JSON sample:

{ "data":{ "curPage":1, "datas":[ { "apkLink":"", "audit":1, "author":"wo5813288", "canEdit":false, "chapterId":294, "ChapterName ":" complete project ", "collect":false, "courseId":13, "desc":" Update learn flutter, so make an application to practice flutter. This application has also developed a lot of content. The main purpose of this project is to get familiar with the writing method of flutter tree structure and UI components. The popular third-party framework for Flutter is also used in the project. "envelopePic":"https://www.wanandroid.com/blogimgs/e092cd25-3e43-42c4-a7eb-b1ebc60ce02a.png", "fresh":true, "host":"", "Id" : 18624, "link" : "https://www.wanandroid.com/blog/show/3020", "niceDate" : "10 hours before", "niceShareDate" : "" ten hours ago, "origin":"", "prefix":"", "projectLink":"https://github.com/wo5813288/wan_giao", "publishTime":1623768707000, "realSuperChapterId":293, "selfVisible":0, "shareDate":1623768707000, "shareUser":"", "superChapterId":294, "SuperChapterName" : "open source projects the main Tab", "tags" : [{" name ":" the project ", "url" : "/ project/list / 1? Cid = 294"}]. "Title" : "the WanAndroid Flutter development", "type" : "userId" : 1, 0, "visible" : 1, "zan" : 0}], "offset" : 0, "over" : false, "pageCount":18, "size":15, "total":261 }, "errorCode":0, "errorMsg":"" }Copy the code

From the above two interfaces and the JSON sample, we can draw the following conclusions:

    1. baseUrlDetermined to behttps://www.wanandroid.com/
    1. Two interfaces:project/tree/jsonwithProject /list/ page count /json? Cid = Incoming ID
    1. Basic generic JSON templates:
{"data": service data" errorCode":0, "errorMsg":""}Copy the code

So we can create a new api.swift file in our code and organize the related Api:

Struct Api {/ / / baseUrl static let baseUrl = "https://www.wanandroid.com/" / / / private initialization method, Private init() {} /// All items are GET request enum Project {static let tags = "Project /tree/json" static let tagList = "project/list/" } }Copy the code

Define the Project service through Moya

Import Foundation import Moya enum ProjectService {case tagList(_ id: Int, _ page: Int) } extension ProjectService: TargetType { var baseURL: URL { return URL(string: Api.baseUrl)! } var path: String { switch self { case .tags: return Api.Project.tags case .tagList(_, let page): return Api.Project.tagList + page.toString + "/json" } } var method: Moya.Method { return .get } var sampleData: Data { return Data() } var task: Task { switch self { case .tags: return .requestParameters(parameters: Dictionary.empty, encoding: URLEncoding.default) case .tagList(let id, _): return .requestParameters(parameters: ["cid": id.toString], encoding: URLEncoding.default) } } var headers: [String : String]? { return nil } }Copy the code

In the above code, I simply used the two categories Int and String, and also attached:

extension Int {
    var toString: String { "\(self)" }
}

extension Dictionary {
    static var empty: Dictionary { [:] }
}
Copy the code

Finally, write a separate Provider:

let projectProvider: MoyaProvider<ProjectService> = {
    let stubClosure = { (target: ProjectService) -> StubBehavior in
        return .never
    }
    return MoyaProvider<ProjectService>(stubClosure: stubClosure, plugins: [RequestLoadingPlugin()])
}()
Copy the code

The RequestLoadingPlugin, which I mentioned in my introduction to Moya, is a plug-in that I won’t go into here.

Write a basic BaseModel based on the JSON format:

Play Android background return JSON basic format, behind the different business is only the value of the data is different:

Import Foundation struct BaseModel<T: Codable>: Codable {// let data: T? let errorCode : Int? let errorMsg : String? }Copy the code

Basic calls to Moya:

The request returns Result

. In the successful Result, we can get Response, the swift. data type of the data obtained through response.data. Convert to the corresponding model through Codable protocol.
,>

projectProvider.request(ProjectService.tags) { (result: Result<Response, MoyaError>) in
    switch result {
    case .success(let response):
        let data = response.data
    case .failure(let error):
        break
    }
}
Copy the code

conclusion

This article explains the considerations for writing network request modules.

I wrote the Api, Moya service and BaseModel by giving examples of two interfaces to play with android projects, and the rest of the interfaces can be written in the same way.

Native Moya calls cannot be translated directly into Codable models, but there are extension methods in Moya.Response to convert them. This will be optimized later via RxMoya.

Tomorrow to continue

In the next article, I’ll abstract away some basic models by playing with some models in Android. It’s basically time to summarize the article while writing the code.

Come on, everybody!