Search code examples
swiftrx-swiftmoya

How i can send orderId received after answering from api?Swift


Hoe i can save orderId and retrieve from Disk and send second Request answer from base:

{"orderId" : 241,"fullName" : "Поесть"}

SearchResponse.swift

struct SearchResponse: Codable {

    var orderId: Int
    var fullName: String
    var retailId: Int

    private enum CodingKeys: String, CodingKey {
        case orderId
        case fullName
        case retailId
    }
}

after search request i try to save orderId in disk like this in status == 200(service.swift):

if let value = result.value {
    var code = 0;
    do {
        if let responseDictionary = try JSONSerialization.jsonObject(with: value.data, options: .allowFragments) as? [String:Any] {
            code = responseDictionary["status"] as? Int ?? 0;
        }

    } catch {
        if let e = try? JSONDecoder().decode(ErrorResponse.self, from: value.data) {
            observer.onError(e);
        }
    }
    if (value.response?.statusCode == 200) {
        do{

            let response = try JSONDecoder().decode(SearchResponse.self, from: value.data);
            try Disk.save(response.retailId, to: .caches, as: FileName.retailName);
            try Disk.save(response.orderId, to: .caches, as: FileName.orderId);


        } catch {
            if let e = try? JSONDecoder().decode(ErrorResponse.self, from: value.data) {
                observer.onError(e);
            }
        }
        observer.onNext(true)
    } else {
        if let e = try? JSONDecoder().decode(ErrorResponse.self, from: value.data) {
            observer.onError(e);
        }
    }
}

viewmodel.swift

private var orderId: String {
    let orderId = try? Disk.retrieve(FileName.orderId, from: .caches, as: SearchResponse.self).orderId
    return String(orderId!) <-- there error "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"
}

Solution

  • This is not a complete answer but I think it is clearer to explain as an answer. You should not use try? but instead catch any error and print them and furthermore avoid forced unwrapping.

    private var orderId: String? {
        do {
            let orderId = try Disk.retrieve(FileName.orderId, from: .caches, as: SearchResponse.self).orderId
            return String(orderId)
        } catch {
            print(error)
        }
        return nil
    }
    

    Now you will get an error message printed to the console if anything goes wrong or you will get nil back if nothing was found which separate two possible issues.

    When saving to disk your error handling is only concerned with json decoding errors so you need to print/handle any possible errors generated from try Disk.save(... as well