Git Product home page Git Product logo

combinealamofireapi's Introduction

CombineAlamofireAPI

Alamofire API Request by Combine framework

License: MIT iOS

SPM

Swift 5

Alamofire API Request by Combine framework

Installation

Dependency

Alamofire

Manually

  1. Download and drop Source folder with files in your project.
  2. Add your API end point URL in your project.
  3. Congratulations!

SPM (Swift Package Manager)

In Xcode, use the menu File > Swift Packages > Add Package Dependency... and enter the package URL https://github.com/Jigneshmayani90/CombineAlamofireAPI.

Usage example

To run the example project, clone the repo, and run spm from the Example directory first.

/// Uses
let createCustomSession = Session()
let request =  RRCombineAlamofireAPI.shared
                  .setSessionManager(createCustomSession) //`Session` creates and manages Alamofire's `Request` types during their lifetimes.
                  .setHttpMethod(.get) // httpMethod: GET, POST, PUT & DELETE
                  .setURL("Your API URL")
                  .setHeaders([:]) // a dictionary of parameters to apply to a `HTTPHeaders`.
                  .setParameter([:]) // a dictionary of parameters to apply to a `URLRequest`.

request.subscribe(on: DispatchQueue.global())
    .receive(on: DispatchQueue.main)
    .sink { (completion) in
       switch completion {
       case .finished:
           break
       case .failure(let error):
           print(error.localizedDescription)
       }
    } receiveValue: { (response) in
        /// The response of data type is Data.
        /// <#T##Here: decode JSON Data into your custom model structure / class#>
        print(response)
    }
    .cancel()


/// Example 1
/// Loader start
let userIds = [1, 2, 3]
Just(userIds)
    .setFailureType(to: Error.self)
    .flatMap { (values) -> AnyPublisher<[User], Error> in
        let tasks = values.publisher.flatMap { userId in
                         RRCombineAlamofireAPI.shared.setURL("https://jsonplaceholder.typicode.com/users/\(userId)")
                                .map { $0 }
                                .decode(type: User.self, decoder: JSONDecoder())
                                .setDeferred()
                    }
        return Publishers.MergeMany(tasks).collect().setDeferred()
    }
    .subscribeAndReceivedData { (allUsers) in
        print("Got users:")
        /// Loader stop
    }

/// Example 2
/// Loader start
RRCombineAlamofireAPI.shared.setURL("https://jsonplaceholder.typicode.com/users/1")
    .flatMap { response -> AnyPublisher<Data, Error> in
        let data = User.decodeJsonData(response)
        print(data?.username ?? "")
        return RRCombineAlamofireAPI.shared.setURL("https://jsonplaceholder.typicode.com/users/2")
                //.delay(for: .seconds(1), scheduler: RunLoop.main)
                .setDeferred()
    }
    .subscribeAndReceivedData { (response) in
        guard let data = response as? Data else { return }
        let user = User.decodeJsonData(data)
        print(user?.username ?? "")
        /// Loader stop
    }


It's not part of SPM
////  subscribeAndReceivedData & Deferred as Publisher extension functions for reuse
extension Publisher {
    // MARK: - Subscribe And Received Data From Server -
    func subscribeAndReceivedData(_ qos: DispatchQoS = .background, data: @escaping((Any) -> ())) {
        subscribe(on: DispatchQueue( label: "rrcombine.queue.\(qos)", qos: qos, attributes: [.concurrent], target: nil))
            .receive(on: DispatchQueue.main)
            .sink { (completion) in
                switch completion {
                case .finished:
                    break
                case .failure(let error):
                    print(error.localizedDescription)
                    /// UIAlertController
                }
                /// Loader stop
            } receiveValue: { response in
                data(response)
            }.cancel()
    }
    // MARK: - Deferred -
    func setDeferred() -> AnyPublisher<Self.Output, Self.Failure> {
        Deferred { self }
            .eraseToAnyPublisher()
    }
}

Contribute

We would love you for the contribution to CombineAlamofireAPI, check the LICENSE file for more info.

License

CombineAlamofireAPI is available under the MIT license. See the LICENSE file for more info.

combinealamofireapi's People

Contributors

jigneshmayani90 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.