Finished with error [-999]

enum APIError: Error {
case invalidBody
case invalidEndpoint
case invalidURL
case emptyData
case invalidJSON
case invalidResponse
case statusCode(Int)
}
import UIKit
import Foundation
import Combine
class Publishers:UIViewController {

static func api(url:String) throws -> URLSession.DataTaskPublisher {
    
    let headers = [ "Content-Type": "application/json",
    "cache-control": "no-cache" ]
    
   // let encoder = JSONEncoder()
       
    guard let url = URL(string: url ) else {
        throw APIError.invalidEndpoint
    }
    
    var request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
    
    request.httpMethod = "GET"
    request.allHTTPHeaderFields = headers

// if model != nil{
// guard let postData = try? encoder.encode(model.self) else {
// throw APIError.invalidBody
// }
// request.httpBody = postData as Data
// }

    let session = URLSession.shared
    
    return session.dataTaskPublisher(for: request)
    
}

}

//MARK: View Controller

let postUserPublisher = try ! Publishers.api( url: "http://dummy.restapiexample.com/api/v1/employees")

func getData(){

let publisher = postUserPublisher
.map({$0})

        .receive(on: RunLoop.main)
               .sink(receiveCompletion: { (completionError) in
                   switch completionError {
                       case .failure(let error):
                           print(error.localizedDescription)
                       case .finished:
                       break
                   }
               }) { (data) in
                  
                self.data = try? JSONDecoder().decode(Welcome.self, from: data.data)
                self.tblVw.reloadData()
                   
           }

}

It looks like there are two issues going on here; first sink returns AnyCancellable so try and return the subscription stream to a Cancellable. Next, when you do this you will run into an ATS failure because you are using HTTP. Setup HTTPS and you should be on your way.

var subscription: Cancellable? = nil

...

do {
    postUserPublisher = try Publishers.api( url: "http://dummy.restapiexample.com/api/v1/employees")
    getData()
} catch {
    print("Error: \(Error.self)")
}


func getData(){
    subscription = postUserPublisher?.sink(
        receiveCompletion: { completion in
            switch completion {
            case .finished:
                break
            case .failure(let error):
                print(error.localizedDescription)
            }
        },
        receiveValue: { (data) in
            print("Response: \(data.response.description)")
        }
    )
}

Matt Eaton

Thanks Matt Eaton,
Its working now

private var apiCancellable: Cancellable? {
didSet { oldValue?.cancel() }
}

deinit {
    apiCancellable?.cancel()
}

No problem. Are you setting apiCancellable to the return of sink?

No @meaton

Terms of Service

Privacy Policy

Cookie Policy