Giter Site home page Giter Site logo

swiftynetworking's Introduction

SwiftyNetworking

CI Status Version License Platform

Features

  • Direct targeted model object decoding
  • Passing parameters as model
  • Uploading jpg/png images as MultipartFormData
  • Instance download image with direct cache cabability
  • Download file as data download request
  • HTTP Response Validation
  • Network Reachability
  • Singleton Free
  • Backgorund Tasks

Requirements

  • iOS 11+
  • Xcode 10.1+
  • Swift 4.2+

Installation

CocoaPods

SwiftyNetworking is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'SwiftyNetworking'

HTTP Requests Examples

To run the example project, clone the repo, and run pod install from the Example directory first. ####Data Request - Returns model object

// Targeted model object
    struct UserModel: Codable {
        let userId: Float
        let id: Float
        let title: String
        let completed: Bool
    }
// Error targeted model object
    struct CommonErrorModel: Codable {
        let message: String
        let error: Error
    }
// Request
let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")
let headers: [String: Any] = ["Authorization": "76GTLYj8j2"]
// headers are optional

    SwiftyNetworking.requestModelResponse(URL: url!, Headers: headers, HTTPMethod: .get) { (result: ModelResult<UserModel,CommonErrorModel>, statusCode) in

        switch result {
        case .success(let user):
            print(user.title)

        case .catchError(let errorModel):
            print(errorModel)

        case .failure(let error):
            print(error.localizedDescription)
        }
    }

####Data Request - With Parameters - Returns model object

// Parameters model
    struct UserRequiredInfoModel: Codable{
        let Id: Int
        let status: Bool

        init(ID: Int, Status: Bool){
            self.Id = ID
            self.status = Status
        }
    }
// Request
let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")
let parameters = UserRequiredInfoModel(ID: 112239, Status: false)
let headers: [String: Any] = ["Authorization": "76GTLYj8j2"]
// headers are optional

    SwiftyNetworking.requestModelResponse(URL: url!, Parameters: parameters, Headers: headers, HTTPMethod: .get) { (result: ModelResult<UserModel,CommonErrorModel>, statusCode) in

        switch result {
        case .success(let user):
            print(user.title)

        case .catchError(let errorModel):
            print(errorModel)

        case .failure(let error):
            print(error.localizedDescription)
        }
    }

####Data Request - Returns JSON

let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")
let headers: [String: Any] = ["Authorization": "76GTLYj8j2"]
// headers are optional

    SwiftyNetworking.requestJsonResponse(URL: url!, Headers: headers, HTTPMethod: .get) { (result, statusCode) in
        switch result {
        case .success(let jsonResponse):
            print(jsonResponse)
        case .failure(let error):
            print(error.localizedDescription)
        }
    }

####Data Request - Returns data as Data

    SwiftyNetworking.requestDataResponse(URL: url!, Headers: nil, HTTPMethod: .get) { (result, statusCode) in

        switch result {
        case .success(let data):
        // Do whatever you want
            print(data)
            return
        case .failure(let error):
            print(error)
        }
    }

Download Image Examples

####Download Image with Caching - Loading Indicator On

// loading indicator - Defualt color
    imageView.downloadImage(urlString: "https://images.unsplash.com/photo-1515627909249-5a98b247c9f2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1500&q=80", loadingIndicator: true) { (Error) in
        if let error = Error {
            print(error.localizedDescription)
        }
    }

// loading indicator - Custom color
    imageView.downloadImage(urlString: "https://images.unsplash.com/photo-1515627909249-5a98b247c9f2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1500&q=80", loadingIndicator: true, IndicatorColor: UIColor.red) { (Error) in
        if let error = Error {
            print(error.localizedDescription)
        }
    }

####Download Image - Returns downloaded image

    let tempImage = UIImageView()
    tempImage.downloadImage(urlString: "https://images.unsplash.com/photo-1515627909249-5a98b247c9f2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1500&q=80") { (downloadedImage, Error) in

        if let error = Error {
            print(error.localizedDescription)
            return
        }

        // Do what you want with the downloaded image
    }

####Delete Image Cache

// Delete image cache
    SwiftyNetworking.deleteImageCache(urlString: "https://images.unsplash.com/photo-1515627909249-5a98b247c9f2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1500&q=80")

// Delete all cached images
    SwiftyNetworking.deleteAllImageCache()

Upload Image Example

####Upload Image as MultipartFormData

let uploadURL = URL(string: "https://api.imgur.com/3/image")
let headers: [String: String] = [
    "Authorization": "Client-ID 341be54e0da4496"
]
// headers are optional

let parameters: [String: Any] = [
    "name": "Image1",
    "description": "Photo Image"
]

let media = Media(withImage: UIImage(named: "PhoneICON")!, imageName: "ramy", forKey: "image", mimeType: .pngImage, withCompression: 1)

SwiftyNetworking.uploadImageWithJsonResponse(Images: [media!], URL: uploadURL!, Parameters: parameters, Headers: headers) { (result, statusCode) in

    switch result {
    case .success(let jsonResult):
        print(jsonResult)
        print(statusCode)
        return
    case .failure(let error):
        print(error)
        print(statusCode)
        return
    }
}

Author

ramysabry22, [email protected]

License

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

swiftynetworking's People

Contributors

ramysabryali avatar

Watchers

 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.