A Chinese version of this document can be found here.
You're a smart developer. You probably use Alamofire to abstract away access to
URLSession
and all those nasty details you don't really care about. But then,
like lots of smart developers, you write ad hoc network abstraction layers. They
are probably called "APIManager" or "NetworkModel", and they always end in tears.
Ad hoc network layers are common in iOS apps. They're bad for a few reasons:
So the basic idea of Moya is that we want some network abstraction layer that sufficiently encapsulates actually calling Alamofire directly. It should be simple enough that common things are easy, but comprehensive enough that complicated things are also easy.
If you use Alamofire to abstract away
URLSession
, why not use something to abstract away the nitty gritty of URLs, parameters, etc?
Some awesome features of Moya:
You can check out more about the project direction in the vision document.
We have provided two sample projects in the repository. To use it download the repo, run carthage update
to download the required libraries and open Moya.xcodeproj. You'll see two schemes: Basic
and Multi-Target
- select one and then build & run! Source files for these are in the Examples
directory in project navigator. Have fun!
This project is actively under development, and is being used in Artsy's auction app. We consider it ready for production use.
Below is a table that shows which version of Moya you should use for your Swift version.
Swift | Moya | RxMoya | ReactiveMoya | RxSwift | ReactiveSwift | Alamofire |
---|---|---|---|---|---|---|
>= 5.2 | >= 15.0.0 | >= 15.0.0 | >= 15.0.0 | 6.X | 6.X | 5.X |
5.X | >= 14.0.0 | >= 14.0.0 | >= 14.0.0 | 5.X | 6.X | 5.X |
5.X | >= 13.0.0 | >= 13.0.0 | >= 13.0.0 | 4.X | 5.X | >= 4.1 |
4.X | 9.0.0 - 12.0.1 | 10.0.0 - 12.0.1 | 9.0.0 - 12.0.1 | 4.X(>= 10.0.0) | 4.X(>= 12.0.0) | 4.1(>= 11.0.0) |
3.X | 8.0.0 - 8.0.5 | 8.0.0 - 8.0.5 | 8.0.0 - 8.0.5 | - | - | - |
2.3 | 7.0.2 - 7.0.4 | 7.0.2 - 7.0.4 | 7.0.2 - 7.0.4 | - | - | - |
2.2 | <= 7.0.1 | <= 7.0.1 | <= 7.0.1 | - | - | - |
Note: If you are using Swift 4.2 in your project, but you are using Xcode 10.2, Moya 13 should work correctly even though we use Swift 5.0.
Upgrading to a new major version of Moya? Check out our migration guides.
Note: Instructions below are for using SwiftPM without the Xcode UI. It's the easiest to go to your Project Settings -> Swift Packages and add Moya from there.
To integrate using Apple's Swift package manager, without Xcode integration, add the following as a dependency to your Package.swift
:
.package(url: "https://github.com/Moya/Moya.git", .upToNextMajor(from: "15.0.0"))
and then specify "Moya"
as a dependency of the Target in which you wish to use Moya.
If you want to use reactive extensions, add also "ReactiveMoya"
, "RxMoya"
or
"CombineMoya"
as your target dependency respectively.
Here's an example PackageDescription
:
// swift-tools-version:5.3 import PackageDescription let package = Package( name: "MyPackage", products: [ .library( name: "MyPackage", targets: ["MyPackage"]), ], dependencies: [ .package(url: "https://github.com/Moya/Moya.git", .upToNextMajor(from: "15.0.0")) ], targets: [ .target( name: "MyPackage", dependencies: ["ReactiveMoya"]) ] )
Combine note: if you're using CombineMoya, make sure that you use Xcode 11.5.0 or later. With earlier versions of Xcode you will have to manually add Combine as a weakly linked framework to your application target.
Accio is a dependency manager based on SwiftPM which can build frameworks for iOS/macOS/tvOS/watchOS. Therefore the integration steps of Moya are exactly the same as described above. Once your Package.swift
file is configured, run accio update
instead of swift package update
.
For Moya, use the following entry in your Podfile:
pod 'Moya', '~> 15.0' # or pod 'Moya/RxSwift', '~> 15.0' # or pod 'Moya/ReactiveSwift', '~> 15.0' # or pod 'Moya/Combine', '~> 15.0'
Then run pod install
.
In any file you'd like to use Moya in, don't forget to
import the framework with import Moya
.
Carthage users can point to this repository and use whichever
generated framework they'd like, Moya
, RxMoya
, ReactiveMoya
, or
CombineMoya
.
Make the following entry in your Cartfile:
github "Moya/Moya" ~> 15.0
Then run carthage update --use-xcframeworks
.
If this is your first time using Carthage in the project, you'll need to go through some additional steps as explained over at Carthage.
NOTE: At this time, Carthage does not provide a way to build only specific repository submodules. All submodules and their dependencies will be built with the above command. However, you don't need to copy frameworks you aren't using into your project. For instance, if you aren't using
ReactiveSwift
, feel free to delete that framework along withReactiveMoya
from the Carthage Build directory aftercarthage update
completes. Or if you are usingReactiveSwift
but notRxSwift
orCombine
, thenRxMoya
,RxTest
,RxCocoa
,CombineMoya
etc. can safely be deleted.
cd
into your top-level project directory, and run the following command if your project is not initialized as a git repository:$ git init
$ git submodule add https://github.com/Alamofire/Alamofire.git $ git submodule add https://github.com/Moya/Moya.git
Alamofire
folder, and drag the Alamofire.xcodeproj
into the Project Navigator of your application's Xcode project. Do the same with the Moya.xcodeproj
in the Moya
folder.They should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter.
xcodeproj
s match that of your application target in the Project Navigator.+
button under the "Embedded Binaries" section.Alamofire.xcodeproj
folders each with two different versions of the Alamofire.framework
nested inside a Products
folder.It does not matter which
Products
folder you choose from, but it does matter whether you choose the top or bottomAlamofire.framework
.
Alamofire.framework
for iOS and the bottom one for macOS.You can verify which one you selected by inspecting the build log for your project. The build target for
Alamofire
will be listed as eitherAlamofire iOS
,Alamofire macOS
,Alamofire tvOS
orAlamofire watchOS
.
Click on the +
button under "Embedded Binaries" again and add the correct build target for Moya
.
And that's it!
The three frameworks are automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device.
After some setup, using Moya is really simple. You can access an API like this:
provider = MoyaProvider<GitHub>() provider.request(.zen) { result in switch result { case let .success(moyaResponse): let data = moyaResponse.data let statusCode = moyaResponse.statusCode // do something with the response data or statusCode case let .failure(error): // this means there was a network failure - either the request // wasn't sent (connectivity), or no response was received (server // timed out). If the server responds with a 4xx or 5xx error, that // will be sent as a ".success"-ful response. } }
That's a basic example. Many API requests need parameters. Moya encodes these into the enum you use to access the endpoint, like this:
provider = MoyaProvider<GitHub>() provider.request(.userProfile("ashfurrow")) { result in // do something with the result }
No more typos in URLs. No more missing parameter values. No more messing with parameter encoding.
For more examples, see the documentation.
Even cooler are the reactive extensions. Moya provides reactive extensions for ReactiveSwift, RxSwift, and Combine.
ReactiveSwift
extension provides both reactive.request(:callbackQueue:)
and
reactive.requestWithProgress(:callbackQueue:)
methods that immediately return
SignalProducer
s that you can start, bind, map, or whatever you want to do.
To handle errors, for instance, we could do the following:
provider = MoyaProvider<GitHub>() provider.reactive.request(.userProfile("ashfurrow")).start { event in switch event { case let .value(response): image = UIImage(data: response.data) case let .failed(error): print(error) default: break } }
RxSwift
extension also provide both rx.request(:callbackQueue:)
and
rx.requestWithProgress(:callbackQueue:)
methods, but return type is
different for both. In case of a normal rx.request(:callbackQueue)
, the
return type is Single<Response>
which emits either single element or an
error. In case of a rx.requestWithProgress(:callbackQueue:)
, the return
type is Observable<ProgressResponse>
, since we may get multiple events
from progress and one last event which is a response.
To handle errors, for instance, we could do the following:
provider = MoyaProvider<GitHub>() provider.rx.request(.userProfile("ashfurrow")).subscribe { event in switch event { case let .success(response): image = UIImage(data: response.data) case let .error(error): print(error) } }
In addition to the option of using signals instead of callback blocks, there are
also a series of signal operators for RxSwift and ReactiveSwift that will attempt
to map the data received from the network response into either an image, some JSON,
or a string, with mapImage()
, mapJSON()
, and mapString()
, respectively. If the mapping is unsuccessful, you'll get an error on the signal. You also get handy methods
for filtering out certain status codes. This means that you can place your code for
handling API errors like 400's in the same places as code for handling invalid
responses.
Combine
extension provides requestPublisher(:callbackQueue:)
and
requestWithProgressPublisher(:callbackQueue)
returning
AnyPublisher<Response, MoyaError>
and AnyPublisher<ProgressResponse, MoyaError>
respectively.
Here's an example of requestPublisher
usage:
provider = MoyaProvider<GitHub>() let cancellable = provider.requestPublisher(.userProfile("ashfurrow")) .sink(receiveCompletion: { completion in guard case let .failure(error) = completion else { return } print(error) }, receiveValue: { response in image = UIImage(data: response.data) })
Moya has a great community around it and some people have created some very helpful extensions.
Hey! Do you like Moya? Awesome! We could actually really use your help!
Open source isn't just writing code. Moya could use your help with any of the following:
If any of that sounds cool to you, send a pull request! After your first contribution, we will add you as a member to the repo so you can merge pull requests and help steer the ship :ship: You can read more details about that in our contributor guidelines.
Moya's community has a tremendous positive energy, and the maintainers are committed to keeping things awesome. Like in the CocoaPods community, always assume positive intent. Even if a comment sounds mean-spirited, give the person the benefit of the doubt.
Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.
AI数字人视频创作平台
Keevx 一款开 箱即用的AI数字人视频创作平台,广泛适用于电商广告、企业培训与社媒宣传,让全球企业与个人创作者无需拍摄剪辑,就能快速生成多语言、高质量的专业视频。
一站式AI创作平台
提供 AI 驱动的图片、视频生成及数字人等功能,助力创意创作
AI办公助手,复杂任务高效处理
AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!
AI辅助编程,代码自动修复
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。
AI小说写作助手,一站式润色、改写、扩写
蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。
全能AI智能助手,随时解答生活与工作的多样问题
问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。
实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。
一键生成PPT和Word,让学习生活更轻松
讯飞智文是一个利用 AI 技术的项目, 能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。
深度推理能力全新升级,全面对标OpenAI o1
科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。
一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型
Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。
最新AI工具、AI资讯
独家AI资源、AI项目落地