Unbox mappings for Moya network requests, includes ReactiveCocoa and RxSwift support.
Add github JaviLorbada/MoyaUnbox
to your Cartfile
.
Carthage will build three frameworks, MoyaUnbox
, RxMoyaUnbox
and ReactiveMoyaUnbox
, once then just import the one you need depends on your preference.
First you need to create your model, for example a GitHub user based on their user API.
struct GHUser {
let login: String
let identifier: Int
let avatarURL: NSURL
…
}
extension GHUser: Unboxable {
init(unboxer: Unboxer) {
self.login = unboxer.unbox("login")
self.identifier = unboxer.unbox("id")
self.avatarURL = unboxer.unbox("avatar_url")
…
}
}
Then you need do the mappings.
After you create your own API provider like
let provider = MoyaProvider<GitHubAPI>(plugins: [NetworkLoggerPlugin(verbose: true)])
you could use mapObject
and mapArray
for the response:
provider.request(.UserProfile("octocat"),
completion: { result in
do {
if let user = try result.value?.mapObject(GHUser) {
print("User: \(user)")
} else {
print(result.error)
}
} catch {
print(error)
}
})
If you use Moya RxSwift extensions, you can use RxMoyaUnbox
extension.
provider.request(.UserProfile("JaviLorbada"))
.filterSuccessfulStatusCodes()
.mapObject(GHUser)
.observeOn(MainScheduler.instance)
.subscribe(onNext: { user in
print("User: \(user)")
}, onError: { error in
print(error)
})
.addDisposableTo(disposeBag)
If you use Moya ReactiveCocoa extensions, you can use ReactiveMoyaUnbox
extension.
provider.request(.UserProfile("JaviLorbada"))
.filterSuccessfulStatusCodes()
.mapObject(GHUser)
.observeOn(UIScheduler())
.startWithResult { result in
if let user = result.value {
print("User: \(user)")
} else {
print(result.error)
}
}
The project contains some tests as an example. If you wanna check it out,
- Clone the repo
git clone https://github.com/JaviLorbada/MoyaUnbox
- Run the setup script on
$ bin/setup-iOS
Issues / Pull Requests / Feedback welcome
This project took inspiration on all the other Moya Mappings. If you use any other JSON serialisation library you should check them out.
MoyaUnbox is available under the MIT license. See the LICENSE file for more info.
- Javi Lorbada
- Follow @javi_lorbada on twitter
- http://javilorbada.me/