devxoul / MoyaSugar

🍯 Syntactic sugar for Moya
MIT License
192 stars 30 forks source link

Implementation of SugarTargetType #11

Closed valentinwallet closed 7 years ago

valentinwallet commented 7 years ago

Hi,

I need to put several http headers with my project, that's why I want to use your abstraction of Moya and have something like this :

enum BikeTrackTestRx {
    case userLogIn(mail: String, password: String)
    case userCreate(mail: String, password: String)
}
extension BikeTrackTestRx: SugarTargetType {
    var url: URL {return URL(string: "https://api.herokuapp.com")!}

    var route: Route {
        switch self {
            case .userLogIn(_):
                return .post("/authenticate")
            case .userCreate(_):
                return .post("/signup")
        }
    }

    var params: Parameters? {
        switch self {
        case .userLogIn(let mail, let password):
            return JSONEncoding.default => [
                "mail": "\(mail)",
                "password": "\(password)"
            ]
        case .userCreate(let mail, let password):
            return JSONEncoding.default => [
                "mail": "\(mail)",
                "password": "\(password)"
            ]
        }
    }

    var task: Task {
        return .request
    }

    var sampleData: Data {
        switch self {
        case .userLogIn(_):
            return "{\"username\": \"toto\", \"password\": \"titi\"}".data(using: .utf8)!
        case .userCreate(_):
            return "{\"username\": \"toto\", \"password\": \"titi\"}".data(using: .utf8)!
        }
    }

    var httpHeaderFields: [String: String]? {
        switch self {
        case .userLogIn(_):
                return ["Authorization": "MyKey",
                        "token": "randomToken"]
        default:
            return ["Authorization": "MyKey"]
        }
    }

}

But i got an error : Type 'BikeTrackTestRx' does not conform to protocol 'TargetType'

Maybe I don't have the good version of Moya, so there is my podfile :

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '10.0'
use_frameworks!

target 'Biketrack' do
       pod 'RxCocoa', '~> 3.0.0'
       pod 'Moya-ModelMapper/RxSwift', '~> 4.1.0'
       pod 'MoyaSugar/RxSwift', '~> 0.4'
       pod 'RxOptional'
end

Thanks in advance 😃

devxoul commented 7 years ago

Does it work if you add Moya dependency on Podfile?

valentinwallet commented 7 years ago

I have added the dependency of Moya in my podfile and also reboot my xcode, still the same error

devxoul commented 7 years ago

@Zanclus oh, you should return baseURL. url is an API for override default url behavior.

valentinwallet commented 7 years ago

Okay thanks perfect! I have solved the problem like this :

var baseURL: URL { return URL(string: "https://bike-track-api.herokuapp.com")! }
var url: URL {return self.defaultURL}
devxoul commented 7 years ago

@Zanclus Or, in this case you can just remove url property. It's optional :)