vadymmarkov / Malibu

:surfer: Malibu is a networking library built on promises

Home Page:https://vadymmarkov.github.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Networking class doesn't work

ro6lyo opened this issue · comments

Hi, I just wanted to try the library , but could not manage to make it work, it seems like request is not fired at all.

import UIKit
import Malibu

enum ParseError: Error {
case InvalidJson
}

struct User: CustomStringConvertible {
let id: Int
let name: String
let username: String
let email: String

var description: String {
    return "Id: \(id)\nName: \(name)\nUsername:\(username)\nEmail: \(email)\n"
}

init(dictionary: [String: Any]) throws {
    guard
        let id = dictionary["id"] as? Int,
        let name = dictionary["name"] as? String,
        let username = dictionary["username"] as? String,
        let email = dictionary["email"] as? String
        else {
            throw ParseError.InvalidJson
    }
    
    self.id = id
    self.name = name
    self.username = username
    self.email = email
}

}

enum Endpoint: RequestConvertible {
case fetchUsers
case createUser(id: Int, name: String, username: String, email: String)

static let baseUrl: URLStringConvertible? = "http://jsonplaceholder.typicode.com/"
static let sessionConfiguration: SessionConfiguration = .default

// Additional headers will be used in the each request.
static var headers: [String : String] {
    return ["Accept" : "application/json"]
}

var request: Request {
    switch self {
    case .fetchUsers:
        return Request.get("users", etagPolicy: .disabled)
    case .createUser(let id, let name, let username, let email):
        return Request.post("users", parameters: [
            "id": id,
            "name": name,
            "username": username,
            "email": email])
    }
}

}

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    
    // Create and configure Networking.
    let networking = Networking<Endpoint>()
    
    // Make GET request
    networking.request(.fetchUsers)
        .validate()
        .toJsonArray()
        .then({ data -> [User] in
            return try data.map({ try User(dictionary: $0) })
        })
        .done({ users in
            print("A list of users:\n")
            users.forEach { print($0) }
        })
        .fail({ error in
            print(error)
        })
        .always({ _ in
            /// ...
        })
}

}

@ro6lyo Try to make Networking an instance var to keep a reference to it. In your example I think it's just being deallocated.

Yeah that was it , my mistake