Moya / Moya

Network abstraction layer written in Swift.
https://moya.github.io
MIT License
15.1k stars 1.98k forks source link

Get -999 cancelled when trying getting post after page 1. #2126

Open RoyDeng opened 3 years ago

RoyDeng commented 3 years ago

It always displays the message as shown on the device below ios12.

Output

Moya: 14.0.0

PostService.swift

import Foundation
import RxSwift
import Moya
import RealmSwift

struct PostService: PostServiceType {
    private let api: MoyaProvider<API>
    private let cache: Cache

    init(api: MoyaProvider<API> = MoyaProvider<API>(), cache: Cache = .shared) {
        self.api = api
        self.cache = cache
    }

    func getPosts(page: Int) -> Observable<Result<[Post], KEYPO.Error>> {
        let configuration = Realm.Configuration(deleteRealmIfMigrationNeeded: true)
        let realm = try! Realm(configuration: configuration)

        if let loggedInUser = realm.objects(Common.self).first {
            let target = API.getPosts(userId: loggedInUser.userUniqueId, page: page)

            return api.rx.request(target)
                .map([Post].self)
                .asObservable()
                .execute { self.cache.set(values: $0) }
                .map(Result.success)
                .catchError { error in
                    let moyaError: MoyaError? = error as? MoyaError
                    let response: Response? = moyaError?.response
                    let message = try! JSONDecoder().decode(CustomError.self, from: response!.data)
                    return .just(.failure(.other(message: message.error)))
                }
        } else {
            return .empty()
        }
    }
}

API.swift

import Foundation
import Moya

enum API {
    case getPosts(
        userId: String,
        page: Int
    )
}

extension API: TargetType {
    var baseURL: URL {
        return URL(string: "xxxxxx")!
    }

    var path: String {
        switch self {
        case .getPosts(let params):
            return "/user/\(params.userId)/posts"
    }

    var method: Moya.Method {
        switch self {
        case .getPosts:
            return .post
    }

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

    var task: Task {
        switch self {
        case .getPosts(let value):
            var params: [String: Any] = [:]
            params["page"] = value.page

            return .requestParameters(parameters: params, encoding: JSONEncoding.default)
        }
    }

    var headers: [String : String]? {
        return ["Authorization": "xxxxxx"]
    }
}
stale[bot] commented 3 years ago

This issue has been marked as stale because it has not had recent activity. It will be closed if no further activity occurs.