Network abstraction layer written in Swift.

Overview

Moya 14.0.0

CircleCI codecov.io Carthage compatible Accio supported CocoaPods compatible Swift Package Manager compatible

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.

Moya Overview

Ad hoc network layers are common in iOS apps. They're bad for a few reasons:

  • Makes it hard to write new apps ("where do I begin?")
  • Makes it hard to maintain existing apps ("oh my god, this mess...")
  • Makes it hard to write unit tests ("how do I do this again?")

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:

  • Compile-time checking for correct API endpoint accesses.
  • Lets you define a clear usage of different endpoints with associated enum values.
  • Treats test stubs as first-class citizens so unit testing is super-easy.

You can check out more about the project direction in the vision document.

Sample Projects

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!

Project Status

This project is actively under development, and is being used in Artsy's new auction app. We consider it ready for production use.

Installation

Moya version vs Swift version.

Below is a table that shows which version of Moya you should use for your Swift version.

Swift Moya RxMoya ReactiveMoya
5.X >= 13.0.0 >= 13.0.0 >= 13.0.0
4.X 9.0.0 - 12.0.1 10.0.0 - 12.0.1 9.0.0 - 12.0.1
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.

Swift Package Manager

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: "14.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" or "RxMoya" as your Target dependency respectively. Here's an example PackageDescription:

// swift-tools-version:5.0
import PackageDescription

let package = Package(
    name: "MyPackage",
    products: [
        .library(
            name: "MyPackage",
            targets: ["MyPackage"]),
    ],
    dependencies: [
        .package(url: "https://github.com/Moya/Moya.git", .upToNextMajor(from: "14.0.0"))
    ],
    targets: [
        .target(
            name: "MyPackage",
            dependencies: ["ReactiveMoya"])
    ]
)

Note: If you are using ReactiveMoya, we are using our own fork of ReactiveSwift. This fork adds 2 commits to remove testing dependencies on releases (starting 6.1.0). This is to prevent Xcode Previews on Xcode 11/11.1 to build testing dependencies (FB7316430). If you don't want to use our fork, you can just add another dependency to your SPM package list: [email protected]:ReactiveCocoa/ReactiveSwift.git and it should fetch the original repository.

Accio

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.

CocoaPods

For Moya, use the following entry in your Podfile:

pod 'Moya', '~> 14.0'

# or 

pod 'Moya/RxSwift', '~> 14.0'

# or

pod 'Moya/ReactiveSwift', '~> 14.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

Carthage users can point to this repository and use whichever generated framework they'd like, Moya, RxMoya, or ReactiveMoya.

Make the following entry in your Cartfile:

github "Moya/Moya" ~> 14.0

Then run carthage update.

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 with ReactiveMoya from the Carthage Build directory after carthage update completes. Or if you are using ReactiveSwift but not RxSwift, then RxMoya, RxTest, RxCocoa, etc. can safely be deleted.

Manually

  • Open up Terminal, cd into your top-level project directory, and run the following command if your project is not initialized as a git repository:
$ git init
  • Add Alamofire & Moya as a git submodule by running the following commands:
$ git submodule add https://github.com/Alamofire/Alamofire.git
$ git submodule add https://github.com/Moya/Moya.git
  • Open the new 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.

  • Verify that the deployment targets of the xcodeprojs match that of your application target in the Project Navigator.
  • Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar.
  • In the tab bar at the top of that window, open the "General" panel.
  • Click on the + button under the "Embedded Binaries" section.
  • You will see two different 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 bottom Alamofire.framework.

  • Select the top 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 either Alamofire iOS, Alamofire macOS, Alamofire tvOS or Alamofire 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.

Usage

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.

Reactive Extensions

Even cooler are the reactive extensions. Moya provides reactive extensions for ReactiveSwift and RxSwift.

ReactiveSwift

ReactiveSwift extension provides both reactive.request(:callbackQueue:) and reactive.requestWithProgress(:callbackQueue:) methods that immediately return SignalProducers 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

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.

Community Projects

Moya has a great community around it and some people have created some very helpful extensions.

Contributing

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:

  • Finding (and reporting!) bugs.
  • New feature suggestions.
  • Answering questions on issues.
  • Documentation improvements.
  • Reviewing pull requests.
  • Helping to manage issue priorities.
  • Fixing bugs/new features.

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 🚒 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.

Adding new source files

If you add or remove a source file from Moya, a corresponding change needs to be made to the Moya.xcodeproj project at the root of this repository. This project is used for Carthage. Don't worry, you'll get an automated warning when submitting a pull request if you forget.

Help us improve Moya documentation

Whether you’re a core member or a user trying it out for the first time, you can make a valuable contribution to Moya by improving the documentation. Help us by:

  • sending us feedback about something you thought was confusing or simply missing
  • suggesting better wording or ways of explaining certain topics
  • sending us a pull request via GitHub
  • improving the Chinese documentation

License

Moya is released under an MIT license. See License.md for more information.

Comments
  • Carthage error with RxSwift

    Carthage error with RxSwift

    i installed Moya with Carthage and i get a error in xcode when building because i don't have RxSwift, maybe to have a another branch or something for RxSwift?

    this is the error i get

    dyld: Library not loaded: @rpath/RxSwift.framework/RxSwift
    Referenced from: /Users/marvinnazari/Library/Developer/CoreSimulator/Devices/9A8009C8-48F2-47FD-86A8-7E6251DF5B60/data/Containers/Bundle/Application/CB3D1236-77FF-4664-8EEF-D94DD08CE55D/X.app/Frameworks/Moya.framework/Moya
    Reason: image not found
    
    chore bug? carthage rxmoya 
    opened by MarvinNazari 52
  • [Swift 3.0] Update for Xcode GM Seed.

    [Swift 3.0] Update for Xcode GM Seed.

    Hey guys! πŸŽ‰ I tried to update Moya to the latest Swift 3.0 shipped with Xcode GM Seed. As there is work that still needs to be done, I would use some help with:

    I think together we can make it better πŸ‘ŠCheers!

    enhancement 
    opened by sunshinejr 51
  • Migrate Moya to a swift package manager compatible layout

    Migrate Moya to a swift package manager compatible layout

    Picks off where #698 left off. Closes #870.

    My concerns:

    • [x] Test to make sure the project is still CocoaPods compatible I'm not familiar with Cocoapods, so the new layout is done to Carthage & SPM best practices, but it would be awesome to have a cocoapods person test it and make sure everything still woks :)
    • [x] Update README: I'm sure some of the instructions will have changed, locations of Demos & Tests, pulling down dependencies for Demos, etc.
    • [x] Update CI for new test locations: The tests are currently failing because the tests CircleCI is expecting are no longer in the same. I also have them setup to pull dependencies down with Carthage instead, so we need to set that up. @BasThomas: I remember you offering to take a look

    Future enhancements:

    • Use swift test once #643 is merged
    • [x] Implement the Carthage caching strategy @scottrhoyt & I discussed in #870
    opened by AndrewSB 40
  • [RFC]: extend MoyaBot to automatically follow up with issues & PRs where we're waiting for author response

    [RFC]: extend MoyaBot to automatically follow up with issues & PRs where we're waiting for author response

    I recently saw @KrauseFx's talk on scaling open source communities (great talk, I'd recommend it to everyone who's doing anything at all in open source). https://news.realm.io/news/tryswift-felix-krause-scaling-open-source-communities-github-management

    One of my big take aways was fastlane's fastlane-bot. Which would automatically follow up with issues and close them if there was no response. Right now, a couple of contributors have been manually doing that, but I think it would be awesome if we could add some of fastlane-bot's functionality to our bot so we don't have to politely close stale issues

    Any thoughts from other contributors? Does anyone want to take a shot at implementing that for MoyaBot?

    enhancement question 
    opened by AndrewSB 39
  • Not able to get URLEncoding working correctly when there is

    Not able to get URLEncoding working correctly when there is "?" and the method is "POST"

    I am using the last version of Moya and Alamofire with Swift 3

    I am having trouble when the method is "POST" and there is url encoding

    The url must be: products?id_category=28

    but it is converted to be: products%3Fid_category=28

    which is not working and giving 400 error on the server

    where can I find this conversion and stop it for the requests ?

    Here is the code i used:

    enum MyService {
    	case products(categorytId: Int)
    }
    
    extension MyService : TargetType {
        
        var base: String { return Constants.MyServiceURL }
        var baseURL: URL { return URL(string: base)! }
        
        public var task: Task {
            return .request
        }
    
        var path : String {
            switch self {
            // i tried with and without them, changing the parameters down below
            case .products(let id_category): 
                return "products?id_category=\(id_category)"
            }
        }
    
        var parameterEncoding: ParameterEncoding {
    	    switch self {
    	        case .products:
    	        	//return MyURLEncoding.queryString
    	            return URLEncoding.queryString
    	        default:
    	            return JSONEncoding.default 
    	    }
        }
    
        var parameters : [String : Any]? {
            switch self {
            // here I tried to add them for Testing purpose, i tried with and without them
            case .products(let id_category):
                var params: [String: Any] = [:]
                params["id_category"] = id_category
                return params
            default:
                return nil
            }
        }
    
        // The method must be always post always
        var method : Moya.Method {
            return .post;
        }
    
        var sampleDate : Data {
                return Data()
            }
        }
     }
    
    question stale 
    opened by iballan 36
  • Multipart upload

    Multipart upload

    This the same implementation as #481 but is based on master branch.

    I need to support file upload using Moya and after look at #114 discussion, I decided to implement my own solution.

    I just added a MultipartTargetType protocol and made some extensions to MoyaProvider where the Target matches the new type.

    Here is an example:

    enum MyAwesomeAPI {
      case EndpointWithImageUpload(NSURL)
    }
    // Extend from MultipartTargetType
    extension MyAwesomeAPI: MultipartTargetType {
       var path: ...
       var parameters: ...
       var method: ...
       var sampleData: ...
       var multipartBody:[MultipartFormData] {
            switch self {
            case .EndpointWithImageUpload(let imageUrl):
                    return [MultipartFormData(provider: .File(contentFile), name: "files", mimeType:"image/jpeg", fileName: "photo.jpg")]
            default:
                return []
            }
        }
    }
    // Call the api
    RxMoyaProvider<MyAwesomeAPI>()
        .requestWithProgress(MyAwesomeAPI.CallWithImageUpload(fileUrl))
        .filterCompleted()
        .mapToJSON().....
    

    requestWithProgress method returns a ProgressResponse that contains the progress and the response result when the http call is completed. Use the method filterCompleted() to get the actual Response and filterProgress() to get the progress of the Upload.

    I had some trouble to compile and test the project. I can create some tests and add to this PR if some one help me with that.

    Thank you and enjoy!

    opened by leonereveel 36
  • Updated project to support Carthage

    Updated project to support Carthage

    This PR adds full support for Carthage, and a solution to using RxSwift and ReactiveCocoa without mandating it for those who wish to use pure Moya.

    • Adds ReactiveMoya and RxMoya targets
    • Adds RAC 3.0 support to ReactiveCocoaMoyaProvider
    • Expands the example project to include demonstrations using reactive extensions
    opened by justinmakaila 36
  • Create and use MoyaError type for SignalProducers.

    Create and use MoyaError type for SignalProducers.

    I took a blind stab at the change I was talking about in #288, mostly as an exercise for myself. I think this preserves the data presented previously in the NSErrors' userInfo, while providing a more swift-friendly interface for retrieving it.

    As I said in the issue, I have no idea what I'm doing, but I'd love to hear your thoughts!

    opened by tomburns 35
  • Status code 405 returned for the first POST call of the app even when POST is an allowed method on the API.

    Status code 405 returned for the first POST call of the app even when POST is an allowed method on the API.

    Moya version ->10.0.1

    I am made a LoginAPI class with following method implementation.

    public var method: Moya.Method {
            return .post
        }
    

    The Login Service allows only POST HTTP method. The issue is even after specifying Moya method as POST, the service response returns 405 status code in service call first time. If I retry the same call, status code 200 is returned.

    Logs with 405 status code: Request: https://myURL/login Moya_Logger: [07/01/2018 21:08:54] Request Headers: ["Content-Type": "application/json"] Moya_Logger: [07/01/2018 21:08:54] HTTP Request Method: POST Moya_Logger: [07/01/2018 21:08:54] Request Body: {"password”:”password”,”email”:”[email protected]"} Moya_Logger: [07/01/2018 21:08:54] Response: <NSHTTPURLResponse: 0x608000038ac0> { URL: Request: https://myURL/login } { Status Code: 405, Headers { Allow = ( POST ); Date = ( "Sun, 07 Jan 2018 15:35:42 GMT" ); "Transfer-Encoding" = ( Identity ); } }

    Logs with 200 Status code: Request: https://myURL/login Moya_Logger: [07/01/2018 21:12:35] Request Headers: ["Content-Type": "application/json"] Moya_Logger: [07/01/2018 21:12:35] HTTP Request Method: POST Moya_Logger: [07/01/2018 21:12:35] Request Body: {"password”:”password”,”email”:”[email protected]"} Moya_Logger: [07/01/2018 21:12:38] Response: <NSHTTPURLResponse: 0x60400043ab80> { URL: Request: https://myURL/login } { Status Code: 200, Headers { "Content-Type" = ( "application/json;charset=UTF-8" ); Date = ( "Sun, 07 Jan 2018 15:39:26 GMT" ); "Transfer-Encoding" = ( Identity ); } }

    Points to note:

    1. This url works perfectly in Postman everytime with 200 status code with POST method.
    2. On simulator, this is the behavior first time I run the app (fresh launch of the app). On next run or on retrying , it works.
    3. Tested the api call by refactoring it to an Alamofire call, it works.

    Could someone please help with what could be the possible cause for this?

    question bug? stale 
    opened by shwetachitlangia 34
  • Add optional queue parameter to Reactive providers

    Add optional queue parameter to Reactive providers

    Hello, i implemented callback queue propagation for reactive providers(which address https://github.com/Moya/Moya/issues/1032 https://github.com/Moya/Moya/issues/1048 https://github.com/Moya/Moya/pull/762). I have same complains, that should be resolved before merge.

    Queue vs Scheduler

    I saw several suggestions to use Schedulers instead of queue for RxSwift(and whatever abstraction ReactiveSwift has), but I’m still believe this queue is not what rx provider responsible for, this is Alamofire threading stuff, users may be confused why they should pass scheduler instead of subscribe/observe on(and maybe this moment should be reflected at method comment).

    

We can’t use SchedulerType, case we need DispatchQueue, which unnecessary for abstract scheduler, so we have to constraint which scheduler type user can pass(so, instead of reuse his scheduler, user may be forced to create new just to pass queue).

    RxSwift do several optimizations for Schedulers(and i’m believe ReactiveSwift too), for example it β€œconverts” Concurrent queue to serial(creating new serial queue with old queue as target), which queue should we use in this case(and even, can we still access concurrent queue)? Not sure we can rely on internal queue in future "optimizations" πŸ˜„

    Everything previously said was my own thoughts, but the fact Schedulers configuration is internal(which means we can’t access it outside of module and 3 paragraphs above has no sense) indicates that Krunoslav Zaher don’t want us to use internal queue :)

    Comments

    Maybe we should add reacher comments to method, explicitly indicating that we nor observe, nor subscribe on this queue, we just pass it to Alamofire as a callback queue. If user really want subscription(request method call) to run on queue - he should subscribe on caller side. 
User may create provider with queue and forget about it, which leads to unexpected element generation queue. In current implementation there is no way to pass nil queue to Alamofire, if provider has default queue, and I don’t know is it okay.

    Other stuff

    As far as I understand, I should update Readme(as at this PR). Maybe I shouldn't use ?? operator? Seems it can affect compilation time, so maybe we should sacrifice readability in favour of compilation speed?

    breaking change 
    opened by haritowa 34
  • Flatten enums & parameters into extended Task type

    Flatten enums & parameters into extended Task type

    This solution was dicussed starting here: https://github.com/Moya/Moya/issues/1135#issuecomment-310913115

    Specifically this PR does the following:

    • [x] Remove parameters and parameterEncoding from everywhere
    • [x] Extend Task with different types of request data (e.g. data & compositeEncoded)
    • [x] Flatten the DownloadType and UploadType enums into the Task type
    • [x] Use those new task cases to set url params & http body appropriately
    • [x] Update Tests
    • [x] Update Docs
    • [x] Write a migration guide
    • [x] Add Changelog entry
    • [x] Handle the TODO: comments (exception handling) appropriately

    This solves the most apparent part of #1135 and it probably also solves #314.

    opened by Jeehut 33
  • SPM Package iOS Target iOS 10 -> iOS 11 Update

    SPM Package iOS Target iOS 10 -> iOS 11 Update

    It is an environment that uses Moya using SPM. When I build a project, I can't build because the minimum target for iOS is iOS 10.

    xcode-14-release-notes The XCode 14 release notes show that the minimum build target is iOS 11.

    I changed the iOS platforms version of the Package.swift file to iOS 11.

    opened by HanweeeeLee 2
  • Error mapping image with Moya.

    Error mapping image with Moya.

    I'm encountering an issue when mapping an image. My service works when calling other data. Swapping out Moya with AlamoFireImage produces the desired results.

    enum AvatarService {
        case grabAvatarImage(url: String)
    }
    
    extension AvatarService: TargetType {
        var baseURL: URL {
            URL(string: "https://avatars.githubusercontent.com/u/")!
        }
        
        var path: String {
            switch self {
            case .grabAvatarImage(let url):
                let splitUrl = url.components(separatedBy: "u/")
                return splitUrl.last!
            }
        }
    
    var method: Moya.Method { .get }
        
    var task: Moya.Task { .requestPlain }
    

    Calling from ViewModel:

    func getLanguage() {
            moya.provider.request(.grabAvatarImage(url: avatarUrl)) { [weak self] result in
                switch result {
                case .failure(let error):
                    print("Error fetching Image:", error)
                case .success(let response):
                    guard
                        let self = self,
                        let receivedImage = try? response.mapImage()
                    else {
                        print("πŸ”₯ Failed to map image")
                        return
                    }
                    self.Image = receivedImage()
                }
            }
        }
    
    

    "πŸ”₯ Failed to map image" gets printed in console. Any help would be greatly appreciated. Thanks

    Using Moya 15.0.0 via SwiftPackageManager

    opened by ThaC0derDre 0
  • how to implement rootQueue?

    how to implement rootQueue?

    I have a class:

    class WildcardServerTrustPolicyManager: ServerTrustManager {
        override func serverTrustEvaluator(forHost host: String) throws -> ServerTrustEvaluating? {
            if let policy = evaluators[host] {
                return policy
            }
            var domainComponents = host.split(separator: ".")
            if domainComponents.count > 2 {
                domainComponents[0] = "*"
                let wildcardHost = domainComponents.joined(separator: ".")
                return evaluators[wildcardHost]
            }
            return nil
        }
    }
    
    

    And I build the session for Moya in class GCAlamofireSessionManagerBuilder using builder:

    // session manager creator
        func build() -> Session {
            let delegate = SessionDelegate()
            let rootQueue = DispatchQueue(label: "net.queue.MoyaQueue")
            let queue = OperationQueue()
            queue.maxConcurrentOperationCount = 1
            queue.underlyingQueue = rootQueue
            let manager = WildcardServerTrustPolicyManager(evaluators: policies)
            let urlSession = URLSession(configuration: configuration,
                                        delegate: self,
                                        delegateQueue: queue)
    
            let session = Session(session: urlSession, delegate: delegate, rootQueue: rootQueue, serverTrustManager: manager)
            return session
        }
    

    But I'm not sure that I used it properly.. I need implement:

    
    extension GCAlamofireSessionManagerBuilder: URLSessionDelegate {
        public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
            if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
                if let credential = self.credential {
                    completionHandler(.useCredential, credential)
                } else {
                    completionHandler(.performDefaultHandling, nil)
                }
            } else {
                completionHandler(.performDefaultHandling, nil)
            }
        }
    }
    

    this if full code:

    
    // GCAlamofireSessionManagerBuilder: session manager builder
    class GCAlamofireSessionManagerBuilder: NSObject {
        var policies: [String: ServerTrustEvaluating] = [:]
        var configuration = URLSessionConfiguration.default
        var urlCredentials: [URLCredential] = []
        private var credential: URLCredential?
    
        // builder initializer
        override init() {
            let configuration: URLSessionConfiguration = URLSessionConfiguration.default
            configuration.timeoutIntervalForRequest = 60
            policies = [
                "*.domain.cloud": PinnedCertificatesTrustEvaluator(acceptSelfSignedCertificates: true)
            ]
    
            let certList = GCCertificateUtils.getAllSavedCertificatesDictionaries()
    
            for certData in certList {
                if let certName = certData["certificateHostName"] as? String,
                   let urlCredential = GCCertificateUtils.getURLCredentialWith(host: certName) {
                    urlCredentials.append(urlCredential)
                }
            }
    
            // Get host
            if self.credential == nil {
                let setting = GC_SQLiteSettingManager.sharedInstance() as! GC_SQLiteSettingManager
                if let ipAddress = setting.dicSetting["IPADRESS"] as? String {
                    self.credential = GCCertificateUtils.getURLCredentialWith(host: ipAddress)
                }
            }
        }
        
        // session manager creator
        func build() -> Session {
            let delegate = SessionDelegate()
            let rootQueue = DispatchQueue(label: "net.queue.MoyaQueue")
            let queue = OperationQueue()
            queue.maxConcurrentOperationCount = 1
            queue.underlyingQueue = rootQueue
            let manager = WildcardServerTrustPolicyManager(evaluators: policies)
            let urlSession = URLSession(configuration: configuration,
                                        delegate: self,
                                        delegateQueue: queue)
    
            let session = Session(session: urlSession, delegate: delegate, rootQueue: rootQueue, serverTrustManager: manager)
            return session
        }
    }
    
    extension GCAlamofireSessionManagerBuilder: URLSessionDelegate {
        public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
            if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
                if let credential = self.credential {
                    completionHandler(.useCredential, credential)
                } else {
                    completionHandler(.performDefaultHandling, nil)
                }
            } else {
                completionHandler(.performDefaultHandling, nil)
            }
        }
    }
    
    
    

    Can anyone help me?

    question 
    opened by lexuanquynh 0
  • trackInflights isn't thread-safe

    trackInflights isn't thread-safe

    Moya -> 15.0.0

    Different callbacks for the same service call don't always get called when we have the trackInflights set to true. It appears as though the @Atomic property wrapper around the MoyaProvider.internalInflightRequests property only ensures atomicity of reads/writes with respect to each read or write operation, but not across combined read/write operations, so the following code from MoyaProvider.requestNormal is not atomic across the read and write as it needs to be:

    if trackInflights {
        var inflightCompletionBlocks = self.inflightRequests[endpoint] // <--- this is atomic
        inflightCompletionBlocks?.append(pluginsWithCompletion)
        self.internalInflightRequests[endpoint] = inflightCompletionBlocks // <--- and this is atomic, but not with the read
    
        if inflightCompletionBlocks != nil {
            return cancellableToken
        } else {
            self.internalInflightRequests[endpoint] = [pluginsWithCompletion] // <--- and this is atomic, but not with the read
        }
    }
    

    and later in the same method:

    if self.trackInflights {
        self.inflightRequests[endpoint]?.forEach { $0(result) } // <--- this is atomic
        self.internalInflightRequests.removeValue(forKey: endpoint) // <--- and this is atomic, but not with the read
    } else ...
    

    I think a lock on self.inflightRequests is needed for each of the if trackInflights codepaths

    opened by jfrodden 1
  • MoyaError does not include original URLRequest in all cases

    MoyaError does not include original URLRequest in all cases

    Hi, My problem is that convertResponseToResult function does not always include the original URLRequest So if the error is "No internet" we will get MoyaError.underlying(error, nil), i.e. the error is missing the context of the original request which in my case is important

    For example in my custom plugin, "didReceive(..." when I receive this error I get very limited information about the original request (I can only get some info from TargetType object) and I am unable to match it with willSend function

    Please consider updating the source so that on all errors we have attached the original request

    opened by kamendo 0
Releases(15.0.3)
  • 15.0.3(Aug 12, 2022)

  • 15.0.1(Aug 12, 2022)

  • 15.0.0(Sep 4, 2021)

    [15.0.0] - 2021-09-04

    Added

    • Added NetworkLoggerPlugin.default and NetworkLoggerPlugin.verbose to conveniently access the default plugins. #2095 by @sunshinejr.

    Changed

    • Breaking Change Changed Hashable && Equatable implementation of Endpoint since it was returning false positives. #2101 by @sunshinejr.
    • Breaking Change MultiPartFormData is now Hashable. #2101 by @sunshinejr.
    • Breaking Change AccessTokenPlugin now uses TargetType, instead of AuthorizationType, in the closure to determine the token. Full MultiTarget integration added as well. #2046 by @Coder-ZJQ.
    • Target.sampleData is now automatically implemented as Data() with default protocol extension. #2015 by jdisho.
    • Breaking Change Minimum version of RxSwift is now 6.0. #2120 by @peagasilva.
    • Moya's Swift minimum version is now Swift 5.2. #2120 by @peagasilva.
    • Moya now depends on the latest versions of RxSwift, ReactiveSwift & Alamofire. #2197 by @BasThomas.

    Fixed

    • Fixed an issue where when using trackInflights option in certain circumstances would return a cached response for an endpoint that's not really the same. #2101 by @sunshinejr.
    • Fixed a crash where Combine Publisher would crash when using stubs. #2072 by jshier.
    • Fixed Unit Tests and CI. #2187 by OhKanghoon.
    • Fixed a race condition that could prevent plugin's willSend(_:target:) from being fired. #2192 by anton-plebanovich.
    Source code(tar.gz)
    Source code(zip)
  • 14.0.1(Feb 18, 2021)

  • 15.0.0-alpha.1(Jul 7, 2020)

    This is an early-release version of Moya 15. This includes minimum Swift version bump to 5.1 as well as bringing back Combine support! It's an alpha release since there might be slight breaking changes to the Combine extensions if we find some problems and also there might be improvements that are waiting in PRs.

    Thanks to @MaxDesiatov @BasThomas @LucianoPAlmeida @amaurydavid and everyone else that helped in the newest release! πŸš€

    Changelog

    Added

    Changed

    Source code(tar.gz)
    Source code(zip)
  • 14.0.0(Feb 15, 2020)

    Moya 14.0.0 is finally released! πŸš€ This is a huge amount of work and so I wanted to thank all contributors, especially @amaurydavid, @LucianoPAlmeida, @larryonoff, @hasankose and @fredpi!

    TL;DR Changelog

    • Bumped dependency versions: Alamofire to 5.0, RxSwift to 5.0, ReactiveSwift to 6.0
    • Minimum target version are now in line with Alamofire 5. iOS: 10.0, tvOS: 10.0, macOS: 10.12, watchOS: 3.0
    • Removed Result dependency in favor of Result type introduced in Swift 5
    • NetworkLoggerPlugin have been reworked to allow more customization about the logged request's components
    • RequestType now has sessionHeaders property! These are the headers that are added when the request is added to a session
    • In AccessTokenPlugin the token closure now takes an AuthorizationType as parameter and AuthorizationType.none has been removed in favor of using AuthorizationType?
    • MultiTarget now implements AccessTokenAuthorizable so that the inner target's authorizationType is correctly returned to the AccessTokenPlugin when requested
    • Added SwiftPM testing using swift test and releasing using swift run rocket which allows us to remove testing dependencies for SwiftPM releases
    • and a lot more!

    See migration guides or create an issue and let us help you out :)

    Source code(tar.gz)
    Source code(zip)
  • 14.0.0-beta.6(Dec 9, 2019)

    Another update while we wait for Alamofire to be stable. This time one fix, one small update - hope you will like it! πŸš€

    Note: Unfortunately we introduced the breaking change with the update, but this was a pretty big gain in terms of the plugin usage so we decided to move forward with it. Make sure you see the migration guide to see how you can migrate easily.

    Changelog

    Changed

    • Breaking Change In AccessTokenPlugin, the token closure now takes a AuthorizationType as parameter and AuthorizationType.none has been removed in favor of using AuthorizationType?. #1969 by @amaurydavid.

    Fixed

    • Fixed a data race condition issue and enable TSAN on the test action and CI. #1952 by @LucianoPAlmeida.
    Source code(tar.gz)
    Source code(zip)
  • 14.0.0-beta.5(Oct 27, 2019)

  • 14.0.0-beta.4(Oct 5, 2019)

    Unfortunately we had to remove Combine for now to keep Xcode 10 compatibility 😭 You might want to update to that version ASAP as it's fixing crashes on release builds...

    Changelog

    • Removed Combine extensions for now. Due to problems with weak-linking the framework, it's too difficult to support it with ease using all package managers and also without breaking backwards-compatibility. Probably gonna introduce it once we only support Xcode 11. #1933 by @sunshinejr
    Source code(tar.gz)
    Source code(zip)
  • 14.0.0-beta.3(Sep 27, 2019)

    A lot of fixes in this one! πŸ‘·

    Changelog

    • Fixed an issue with displaying cURL-formatted request in NetworkLoggerPlugin. #1916 by @sunshinejr.
    • Fixed an issue that wouldn't display stubbed response body in NetworkLoggerPlugin. #1916 by @sunshinejr.
    • Fixed an issue where Carthage users using Xcode 11 couldn't install Moya 14. We added weak-linking for the xcodeproj so you might need additional steps for Xcode 10 + Carthage + Moya 14.* users. #1920 by @fredpi and @sunshinejr.
    • Fixed an issue that wouldn't persist URLRequest changes (created by plugins) when stubbed. #1921 by @sunshinejr.
    • Fixed an issue with SPM integration - it no longer fetches testing libraries and also doesn't create runtime/Xcode Preview crashes. #1923 by @sunshinejr.
    Source code(tar.gz)
    Source code(zip)
  • 14.0.0-beta.2(Sep 9, 2019)

  • 14.0.0-beta.1(Sep 6, 2019)

    πŸš€πŸš€πŸš€

    βœ… Combine extensions βœ… NetworkLoggerPlugin rewrite βœ… Alamofire 5.0.0-rc.1

    For NetworkLoggerPlugin, see our migration guide!

    Changelog

    Added

    • Combine support! #1904 by @sunshinejr.
    • Very raw SPM testing support! Thanks to the work on OHHTTPStubs, we can finally start using swift test again. #1896 by @sunshinejr.

    Changed

    • Breaking Change Minimum version of Alamofire is now 5.0.0-rc.1. #1909 by @sunshinejr.
    • Breaking Change The NetworkLoggerPlugin have been reworked to allow more customization about the logged request's components. #1894 by @amaurydavid.
    • Breaking Change Bumped ReactiveSwift version to 6.1.0. This should only affect Carthage users, but you'll probably want to use 6.1.0 in all of your Xcode 11 projects. #1896 by @sunshinejr.
    • NetworkLoggerPlugin now logs error when available (using LogOptions.verbose or specyfing errorResponseBody in your LogOptions). #1880 by @amaurydavid.
    Source code(tar.gz)
    Source code(zip)
  • 14.0.0-alpha.2(Aug 1, 2019)

    This is a pre-release version of Moya 14. This includes removal of Result dependency (now using Swift's Result), upgrade to Alamofire 5 (currently 5.0.0-beta.7) and few more adjustments.

    Changelog

    Added

    • RequestType now has sessionHeaders! These are the headers that are added when the request is added to a session. #1878 by @sunshinejr.

    Changed

    • Breaking Change Minimum target version are now in line with Alamofire 5. iOS: 10.0, tvOS: 10.0, macOS: 10.12, watchOS: 3.0. #1810 by @sunshinejr.
    • Breaking Change Minimum version of Alamofire is now 5.0.0-beta.7. #1810 by @sunshinejr.
    • Breaking Change Removed Result dependency in favor of Result introduced in Swift 5. #1858 by @larryonoff.
    • Breaking Change Added TargetType parameter in the output of NetworkLoggerPlugin. #1866 by @hasankose.
    • NetworkoLoggerPlugin uses the newly added sessionHeaders and now logs all the headers that the request will produce. #1878 by @sunshinejr.
    Source code(tar.gz)
    Source code(zip)
  • 14.0.0-alpha.1(May 14, 2019)

    This is an early pre-release version of Moya 14. This includes newest RxSwift & ReactiveSwift versions. Next pre-releases would have new version of Alamofire and potentially removed Result dependency.

    Changelog

    Changed

    Source code(tar.gz)
    Source code(zip)
  • 13.0.1(May 1, 2019)

  • 13.0.0(Apr 10, 2019)

    Xcode 10.2, Swift 5.0 and more! πŸš€

    Full Changelog for Moya 13.0:

    Note: there are no changes between 13.0.0-beta.1 and 13.0.0.

    Changed

    • Breaking Change .mapImage() extension on Single and Observable now returns non-optional image. #1789, #1799 by @bjarkehs and @sunshinejr.
    • Breaking Change Minimum version of ReactiveSwift is now 5.0. #1817 by @larryonoff.
    • Breaking Change Minimum version of Result is now 4.1. #1817 by @larryonoff.
    • Breaking Change Updated project to Swift 5.0. #1827 by @sunshinejr.
    • Updated project to support Xcode 10.2. #1826 by @larsschwegmann.
    • MoyaError now conforms to CustomNSError protocol, makes underlying errors available in its user-info dictionary. #1783 by @dpoggi.

    Fixed

    • Fixed Progress object on responses that did not specify correct Content-Length header. Now, whenever there is no valid header, the progress will be 0.0 until the completion of the request. Also, the completed property is now true only when the response was serialized, we do not rely on progress being 1.0 anymore. #1815 by @sunshinejr.

    Removed

    • Breaking change Removed validate on TargetType. It was deprecated in Moya 11, use validationType instead. #1828 by @sunshinejr.
    Source code(tar.gz)
    Source code(zip)
  • 13.0.0-beta.1(Mar 31, 2019)

    Xcode 10.2, Swift 5.0 and more! πŸš€

    Changed

    • Breaking Change .mapImage() extension on Single and Observable now returns non-optional image. #1789, #1799 by @bjarkehs and @sunshinejr.
    • Breaking Change Minimum version of ReactiveSwift is now 5.0. #1817 by @larryonoff.
    • Breaking Change Minimum version of Result is now 4.1. #1817 by @larryonoff.
    • Breaking Change Updated project to Swift 5.0. #1827 by @sunshinejr.
    • Updated project to support Xcode 10.2. #1826 by @larsschwegmann.
    • MoyaError now conforms to CustomNSError protocol, makes underlying errors available in its user-info dictionary. #1783 by @dpoggi.

    Fixed

    • Fixed Progress object on responses that did not specify correct Content-Length header. Now, whenever there is no valid header, the progress will be 0.0 until the completion of the request. Also, the completed property is now true only when the response was serialized, we do not rely on progress being 1.0 anymore. #1815 by @sunshinejr.

    Removed

    • Breaking change Removed validate on TargetType. It was deprecated in Moya 11, use validationType instead. #1828 by @sunshinejr.
    Source code(tar.gz)
    Source code(zip)
  • 12.0.1(Nov 19, 2018)

    This release fixes the installation issues for the Moya/RxSwift and Moya/ReactiveSwift subspecs via CocoaPods (#1768). Please use this as the minimum version for 12.x releases.

    Source code(tar.gz)
    Source code(zip)
  • 12.0.0(Nov 19, 2018)

    This release is long overdue but Moya 12.0 is finally here! πŸŽ‰ The latest version of Moya now supports Swift 4.2 as well as version 4.X of RxSwift and 4.X of ReactiveSwift. Additionally, we've made a highly requested addition to the AccessTokenPlugin - the ability to set a header token in a custom format πŸ‘

    Thanks to all the contributors to this release, @SeRG1k17, @sunshinejr, @simonrice, @LucianoPAlmeida, @lexorus, as well as everyone else who makes this project possible ❀️

    Full Changelog for Moya 12.0:

    Added

    • Breaking Change Added .custom(String) authorization case to AuthorizationType inside AccessTokenPlugin. #1611 by @SeRG1k17.

    Changed

    • Breaking Change watchOS deployment target for RxMoya is now 3.0. #1758 by @simonrice.

    • Breaking Change Minimum version of ReactiveSwift is now 4.0. #1668 by @sunshinejr.

    • Breaking Change Minimum version of Result is now 4.0. #1668 by @sunshinejr.

    • Breaking Change Changed Responses filter method parameter to use a generic RangeExpression that accepts any range type. #1624 by @LucianoPAlmeida.

    • Breaking Change Changed AccessTokenPlugin's initializer to no longer use an @autoclosure for the tokenClosure parameter. #1611 by @SeRG1k17.

    Fixed

    • Fix warnings generated by Xcode 10. Updated project to Swift 4.2 #1740 by @lexorus
    Source code(tar.gz)
    Source code(zip)
  • 12.0.0-beta.1(Aug 7, 2018)

    Added

    • Breaking Change Added .custom(String) authorization case to AuthorizationType inside AccessTokenPlugin. #1611 by @SeRG1k17.

    Changed

    • Breaking Change Minimum version of ReactiveSwift is now 4.0. #1668 by @sunshinejr.

    • Breaking Change Minimum version of Result is now 4.0. #1668 by @sunshinejr.

    • Breaking Change Changed Responses filter method parameter to use a generic RangeExpression that accepts any range type. #1624 by @LucianoPAlmeida.

    • Breaking Change Changed AccessTokenPlugin's initializer to no longer use an @autoclosure for the tokenClosure parameter. #1611 by @SeRG1k17.

    Source code(tar.gz)
    Source code(zip)
  • 11.0.2(Apr 1, 2018)

  • 11.0.1(Feb 26, 2018)

    This release fixes a few bugs regarding Alamofire validation not being performed on requests.

    Fixed

    • Fixed Alamofire validation not being performed on .uploadMultipart requests. #1591 by @SD10.
    • Fixed Alamofire validation not being performed on stubbed requests. #1593 by @SD10.
    Source code(tar.gz)
    Source code(zip)
  • 11.0.0(Feb 8, 2018)

    This release brings support for ReactiveSwift 3.0. Thank you to all the contributors making it possible! ❀️

    Full Changelog for Moya 11.0:

    Added

    • Breaking Change Added a .requestCustomJSONEncodable case to Task. #1443 by @evgeny-sureev.
    • Breaking Change Added failsOnEmptyData boolean support for the Decodable map functions. #1508 by @jeroenbb94.

    Changed

    • Breaking Change Updated minimum version of ReactiveSwift to 3.0. #1470 by @larryonoff.
    • Breaking Change Changed the validate property of TargetType to use new ValidationType enum representing valid status codes. #1505 by @SD10, @amaurydavid.
    • Breaking Change Removed generic from Endpoint. See #1524 for discussion. #1529 by @zhongwuzw.
    Source code(tar.gz)
    Source code(zip)
  • 11.0.0-beta.2(Jan 27, 2018)

  • 10.0.2(Jan 26, 2018)

    Fixed

    • Fixed a bug where modifying .uploadMultipart, .uploadCompositeMultipart, .uploadFile, .downloadDestination, and .downloadParameters tasks through an endpointClosure has no effect on the final request. #1550 by @SD10, @sunshinejr.
    • Fixed a bug where URLEncoding.httpBody wasn't allowed as bodyEncoding in Task.requestCompositeParameters(). #1557 by @sunshinejr.
    Source code(tar.gz)
    Source code(zip)
  • 11.0.0-beta.1(Jan 10, 2018)

    This release brings full ReactiveSwift 3.0 support and minor enhancements. Thanks to all contributors that made it possible!

    Added

    • Breaking Change Added a .requestCustomJSONEncodable case to Task. #1443 by @evgeny-sureev.
    • Breaking Change Added failsOnEmptyData boolean support for the Decodable map functions. #1508 by @jeroenbb94.

    Changed

    • Breaking Change Updated minimum version of ReactiveSwift to 3.0. #1470 by @larryonoff.
    • Breaking Change Changed the validate property of TargetType to use new ValidationType enum representing valid status codes. #1505 by @SD10, @amaurydavid.
    Source code(tar.gz)
    Source code(zip)
  • 10.0.1(Nov 23, 2017)

    Nothing better than a few bug fixes after the major release πŸ˜‰

    Fixed

    • Fixed a bug that Decodable mapping to object other than Array and Dictionary in a key path cause crash. #1405 by @ufosky.
    • Fixed a bug with missing Content-Type header when using .requestJSONEncodable #1410 by @Vict0rS.
    • Fixed linker settings, enabling RxMoya and ReactiveMoya to be used in app extensions #1417 by @spookyvision.
    • Fixed carthage OS X not targeting 10.10 #1444 by @lucas34.
    Source code(tar.gz)
    Source code(zip)
    Moya.framework.zip(4.96 MB)
  • 10.0.0(Oct 21, 2017)

    Full Swift 4.0, RxSwift 4.0 support and more! Thanks to all contributors that made it possible:

    @devxoul @SD10 @LeLuckyVint @afonsograca @AndrewSB @BasThomas @pedrovereza @sunshinejr

    Big ❀️ to all of you!

    Changes since 10.0.0-beta.1:

    Fixed

    • Fixed a bug that Decodable mapping won't decode nested JSON array in a key path #1382 by @devxoul.

    Full changelog for Moya 10.0.0:

    Added

    Changed

    • Breaking Change Changed Endpoint.init so it doesn't have any default arguments (removing default argument .get for method parameter and nil for httpHeaderFields parameter). #1289 by @sunshinejr.
    • Breaking Change Changed NetworkActivityPlugin so its networkActivityClosure has now target: TargetType argument in addition to change: NetworkActivityChangeType. #1290 by @sunshinejr.
    • Breaking Change Changed Endpoint's urlRequest property to urlRequest() a throwing method. #1248 by @SD10.

    Removed

    • Breaking Change Removed RxMoyaProvider and ReactiveSwiftMoyaProvider. #1320 by @SD10

    Fixed

    • Fixed a MoyaProvider+Rx self-retaining bug in requestWithProgress. #1311 by @AndrewSB.
    Source code(tar.gz)
    Source code(zip)
    Moya.framework.zip(4.45 MB)
  • 10.0.0-beta.1(Oct 8, 2017)

    Full Swift 4.0 support and more! RxSwift 4.0.0-rc.0 needed for RxSwift 4.0. Thanks to all contributors that made it possible!

    Added

    Changed

    • Breaking Change Changed Endpoint.init so it doesn't have any default arguments (removing default argument .get for method parameter and nil for httpHeaderFields parameter). #1289 by @sunshinejr.
    • Breaking Change Changed NetworkActivityPlugin so its networkActivityClosure has now target: TargetType argument in addition to change: NetworkActivityChangeType. #1290 by @sunshinejr.
    • Breaking Change Changed Endpoint's urlRequest property to urlRequest() a throwing method. #1248 by @SD10.

    Removed

    • Breaking Change Removed RxMoyaProvider and ReactiveSwiftMoyaProvider. #1320 by @SD10

    Fixed

    • Fixed a MoyaProvider+Rx self-retaining bug in requestWithProgress. #1311 by @AndrewSB.
    Source code(tar.gz)
    Source code(zip)
  • 9.0.0(Sep 4, 2017)

    This is a big major release and thanks to everyone involved! πŸŽ‰ πŸŽ‰ πŸŽ‰

    In this release there were two big changes:

    1. We deprecated reactive providers and started using rx and reactive namespaces.
    2. We removed parameters, parameterEncoding and expanded task.

    We also added Swift 4.0 support to Moya core (and preliminary for ReactiveSwift) where support for RxSwift will be in a next major release. We improved our test coverage from 76% up to 83%, added callbackQueues as an option for all requests (reactive or not!), headers to TargetType, improved AccessTokenPlugin, started using Single<Response> instead of Observable<Response> for RxSwift normal requests and many, many more! Checkout the changelog below and have fun! πŸŽ‰ There is also a migration guide to help you make it through!

    Oh, and if you find anything you are concerned about, make a new Issue - or better yet, make a PR with the fix! πŸ˜‰

    Changes since 9.0.0-beta.1:

    • Removed default value for task from Endpoint initializer.

    Full changelog for Moya 9.0.0:

    • Breaking Change Added support to get the response (if any) from MoyaError.
    • Breaking Change Added headers to TargetType.
    • Breaking Change Updated RxMoyaProvider.request to return a Single<Request>.
    • Breaking Change Updated Moya.Response's responseto use an HTTPURLResponse instead of a URLResponse.
    • Breaking Change Updated TargetTypes so it no longer receives the Authorization: Bearer <token> header by default when using AccessTokenPlugin.
    • Breaking Change Renamed all occurrences of queue to callbackQueue.
    • Breaking Change Deprecated ReactiveSwiftMoyaProvider and RxSwiftMoyaProvider. Use MoyaProvider with reactive properties now: provider.reactive._, provider.rx._. In case you were subclassing reactive providers, please take a look at this PR from Eidolon. It covers migration from subclassing given providers, to usage by composition.
    • Breaking Change Removed parameter name in requestWithProgress for ReactiveSwiftMoyaProvider.
    • Breaking Change Removed deprecated in Moya 8.0.0: Moya.Error, endpointByAddingParameters(parameters:), endpointByAddingHttpHeaderFields(httpHeaderFields:), endpointByAddingParameterEncoding(newParameterEncoding:), endpointByAdding(parameters:httpHeaderFields:parameterEncoding), StructTarget, filterStatusCodes(range:), filterStatusCode(code:), willSendRequest(request:target:), didReceiveResponse(result:target:), ReactiveCocoaMoyaProvider, ReactiveSwiftMoyaProvider.request(token:).
    • Breaking Change Replaced parameters & parameterEncoding in TargetType with extended Task cases.
    • Breaking Change Replaced shouldAuthorize: Bool in AccessTokenAuthorizable with authorizationType: AuthorizationType.
    • Breaking Change Replaced token in AccessTokenPlugin with tokenClosure.
    • Breaking Change Flattened UploadType and DownloadType into Task cases.
    • Added optional callback queue parameter to reactive providers.
    • Added public URL(target:) initializator that creates url from TargetType.
    • Added an optional requestDataFormatterin NetworkLoggerPlugin to allow the client to interact with the request data before logging it.
    • Added Swift 4.0 support for Moya core (without RxSwift/ReactiveSwift extensions for now).
    • Added all the filter/map operators that were available for Observable<Response> to Single<Response> as well.
    • Added AuthorizationType to AccessTokenAuthorizable representing request headers of .none, .basic, and .bearer.
    • Added tests for Single<Response> operators.
    • Added Progress object into the response when calling progress callback on completion.
    • Added tests for creating URLRequest from Task.
    • Updated minimum version of RxSwift to 3.3.
    • Updated minimum version of ReactiveSwift to 2.0.
    • Fixed a bug where you would have two response events in requestWithProgress method on ReactiveSwift module.
    • Fixed a bug where you weren't notified on progress callback for data request.
    • Enabled the "Allow app extension API only" flag.
    • Removed default value for task from Endpoint initializer.
    Source code(tar.gz)
    Source code(zip)
Lightweight network abstraction layer, written on top of Alamofire

TRON is a lightweight network abstraction layer, built on top of Alamofire. It can be used to dramatically simplify interacting with RESTful JSON web-

MLSDev 528 Dec 26, 2022
Elegant network abstraction layer in Swift.

Elegant network abstraction layer in Swift. δΈ­ζ–‡ Design Features Requirements Communication Installation Usage Base Usage - Target - Request - Download

null 100 Dec 9, 2022
Dratini is a neat network abstraction layer.

Dratini Dratini is a neat network abstraction layer. If you are looking for a solution to make your network layer neat, Dratini is your choice. Dratin

Kevin Lin 37 Jan 29, 2022
NSURLSession network abstraction layer, using Codable and Decodable for response and Encodable for request. βš™οΈπŸš€

SONetworking NSURLSession network abstraction layer, using Codable and Decodable for response and Encodable for request. Project Folder and File Struc

Ahmad AlSofi 4 Jan 28, 2022
Another network wrapper for URLSession. Built to be simple, small and easy to create tests at the network layer of your application.

Another network wrapper for URLSession. Built to be simple, small and easy to create tests at the network layer of your application. Install Carthage

Ronan Rodrigo Nunes 89 Dec 26, 2022
Say goodbye to the Fat ugly singleton Network Manager with this Network Layer

MHNetwork Protocol Oriented Network Layer Aim to avoid having bloated singleton NetworkManager Philosophy the main philosophy behind MHNetwork is to h

Mohamed Emad Hegab 19 Nov 19, 2022
Easy and lightweight network layer for creating different set of network requests like GET, POST, PUT, DELETE customizable with coders conforming to TopLevelDecoder, TopLevelEncoder

Easy and lightweight network layer for creating different set of network requests like GET, POST, PUT, DELETE customizable with coders conforming to TopLevelDecoder, TopLevelEncoder

Igor 2 Sep 16, 2022
Type-safe networking abstraction layer that associates request type with response type.

APIKit APIKit is a type-safe networking abstraction layer that associates request type with response type. // SearchRepositoriesRequest conforms to Re

Yosuke Ishikawa 1.9k Dec 30, 2022
DBNetworkStack is a network abstraction for fetching request and mapping them to model objects

DBNetworkStack Main Features ?? Typed network resources ?? Value oriented architecture ?? Exchangeable implementations ?? Extendable API ?? Composable

DB Systel GmbH 33 Jan 10, 2022
A generic network layer written in swift

SwiftyNet 1.0.0 A generic network layer written in swift. you can use it as an abstraction layer above Alamofire with generic returned types. Installa

Mohamed Salah Zidane 17 Oct 11, 2021
Alamofire Network Layer written in swift 5 using the protocol oriented, combine, UIKit, MVVM.

CoreAPI-iOS This project Contains Alamofire Network layer Based on Protocol Oriented Concept and Combine Framework. It is created with UIKit, Alamofir

Mehran Kamalifard 27 Nov 11, 2022
Generic Network Layer created using Swift.

Generic-Network-Layer_iOS Generic Network Layer created using URLSession. Networking is an essential element in app development, and you'll need API c

Shubham Kr. Singh 41 Dec 31, 2022
Alamofire network layer

NVNetworkRequest Alamofire network layer Installation Add this to your Package dependencies: dependencies: [ .package(url: "https://github.com/vin

Vinh Nguyen 0 Nov 19, 2021
Async network layer with Combine

Version 1.0.10 Currently Available Platform Version iOS 12.0 tvOS 10.0 macOS 10.15 watchOS 3.0 macCatalyst 13.0 Hover is a Network layer which uses Ap

Onur HΓΌseyin Γ‡antay 124 Oct 23, 2022
iOS 15, MVVM, Async Await, Core Data, Abstract Network Layer, Repository & DAO design patterns, SwiftUI and Combine

iOS 15, MVVM, Async Await, Core Data, Abstract Network Layer, Repository & DAO design patterns, SwiftUI and Combine

Conrado Mateu Gisbert 18 Dec 23, 2022
VFNetwork is a protocol-oriented network layer that will help you assemble your requests in just a few steps.

Simple, Fast and Easy. Introduction VFNetwork is a protocol-oriented network layer that will help you assemble your requests in just a few steps. How

Victor Freitas 4 Aug 22, 2022
NWReachability - a pure Swift library for monitoring the network connection of iOS devices using Apple's Network framework.

NWReachability is a pure Swift library for monitoring the network connection of iOS devices using Apple's Network framework.

null 4 Dec 2, 2022
A network extension app to block a user input URI. Meant as a network extension filter proof of concept.

URIBlockNE A network extension app to block a user input URI. Meant as a network extension filter proof of concept. This is just a research effort to

Charles Edge 5 Oct 17, 2022
Elegant API Abstraction for Swift

Endpoint (Deprecated) ⚠️ This project has been deprecated. Consider using Moya and MoyaSugar instead. ?? Elegant API Abstraction for Swift. At a Glanc

Suyeol Jeon 35 Mar 29, 2019