Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Last active November 14, 2019 02:02
Show Gist options
  • Save robertmryan/03542e2da539ad7f51c2540bafdad97e to your computer and use it in GitHub Desktop.
Save robertmryan/03542e2da539ad7f51c2540bafdad97e to your computer and use it in GitHub Desktop.
struct Cost: Codable {
let id: String
let label: String
let value: String
}
let cost = Cost(id: "something", label: "something", value: "something")
let jsonData = try! JSONEncoder().encode(cost) // this works fine
let object = try! JSONSerialization.jsonObject(with: jsonData) // this works fine
@MohsenMoghimi
Copy link

hi again my friend, I'm have issue with my network layer, would you please help me???

@robertmryan
Copy link
Author

Go ahead an add your question here. Worst case scenario, if it’s too complicated, I might suggest that you post it as a proper question on StackOverflow, as I’m buried right now.

@MohsenMoghimi
Copy link

I really don't know about it complication, I will ask and you take decision that its complicated or not.

@MohsenMoghimi
Copy link

MohsenMoghimi commented Nov 13, 2019

I have APIClient in my project and this is the code:

protocol APIClientType {
    func request<M: Codable>(_ endpoint: URLRequestConvertible) -> Single<M>
}

final class NewAPIClient: NSObject, URLSessionDelegate, APIClientType {
    
    var session: URLSession!
    
    override init() {
        super.init()
        
        let urlsession = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue.main)
        urlsession.configuration.allowsCellularAccess = true
        urlsession.configuration.timeoutIntervalForRequest = TimeInterval(10.0)
        
        self.session = urlsession
    }
    
    func request<M: Codable>(_ endpoint: URLRequestConvertible) -> Single<M> {
        return Single<M>.create { [unowned self] single in

            let request = endpoint.request()

            #if DEBUG
            print("REQUEST: \(debugPrint(request))")
            #endif
            
            let task = self.session.dataTask(with: request) { (data, response, error) in
                if let responseError = error {
                    single(.error(responseError))
                }
                
                #if DEBUG
                print("RESPONSE: \(debugPrint(response ?? "NULL"))")
                #endif
                
                if let httpResponse = response as? HTTPURLResponse {
                    switch httpResponse.statusCode {
                    case 200, 201:
                        guard let data = data else {
                            break
                        }
                        
                        do {
                            let model = try JSONDecoder().decode(M.self, from: data)
                            single(.success(model))
                        } catch let myJSONError {
                            single(.error(myJSONError))
                        }
                        
                    case 404:
                        single(.error(APIError.NotFound))
                        
                    default:
                        break
                    }
                }
            }
            
            task.resume()
            
            return Disposables.create {
                task.cancel()
            }
        }
    }
}

@MohsenMoghimi
Copy link

MohsenMoghimi commented Nov 13, 2019

in 2 case of web services the response is simple text not a json, something like "the task done", my issue is when I intent to get this responses the " request " function returns myJSONError, how can I modify this class to return a simple string response?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment