Elegant network abstraction layer in Swift.

Overview

SLNetwork

CocoaPods Compatible Carthage Compatible Platform

Elegant network abstraction layer in Swift.


Design

Alamofire and Moya are elegant Swift network frames. They each have their own advantages. When I use them, I always want to combine the advantages of both, make them easy to use and retain their original features. So I wrote the SolarNetwork.

  • SLNetwork corresponds to a SessionManager.
  • SLTarget corresponds to a Host, or a set of requests for the same configuration.
  • SLRequest, SLDownloadRequest, SLUploadRequest corresponds to Request of Data, Download, Upload.
  • SLProgress return progress when download or upload.
  • SLResponse response of a request which you can decode to JsonObject or Model.
  • SLPlugin you can modify SLRequest in willSend and modify SLResponse in didReceive.
  • SLReflection reflex properties of SubSLRequest to Alamofire.Parameters.

So a complete request process is:

SLNetwork(SLTarget).request(SLRequest).willSend(SLRequest)
                   .progressClosure(SLProgress)
                   .reponseData(OriginalResponse)
                   .didReceive(SLResponse).decodeTo(Dictionary)
                   .completionClosure(SLResponse)
                   .decodeTo(Model: Decodable).dealWithError

In most cases, what you need to concerned about is:

SLNetwork(SLTarget).request(SLRequest)
                   .progressClosure(SLProgress)
                   .completionClosure(SLResponse)

Features

  • URL / JSON / plist Parameter Encoding
  • Upload File / Data / Stream / MultipartFormData
  • Download File using Request or Resume Data
  • Authentication with URLCredential
  • Upload and Download Progress Closures with Progress
  • Dynamically Adapt and Retry Requests
  • TLS Certificate and Public Key Pinning
  • Network Reachability
  • Pre-populate the DNS cache
  • Complete Logger

Requirements

  • iOS 8.0+
  • Xcode 9+
  • Swift 4+

Communication

  • If you'd like to ask a general question, use Stack Overflow.
  • If you found a bug, open an issue.
  • If you have a feature request, open an issue.
  • If you want to contribute, submit a pull request.

Installation

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. You can install it with the following command:

$ gem install cocoapods

CocoaPods 1.1+ is required.

To integrate SolarNetwork into your Xcode project using CocoaPods, specify it in your Podfile:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

target '<Your Target Name>' do
    pod 'SolarNetwork'
end

Then, run the following command:

$ pod install

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate Alamofire into your Xcode project using Carthage, specify it in your Cartfile:

github "ThreeGayHub/SolarNetwork"

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.


Usage

Base Usage

Target

import SolarNetwork

struct HTTPBinTarget: SLTarget {
    var baseURLString: String { return "https://httpbin.org" }
}

let HTTPBinNetwork = SLNetwork(HTTPBinTarget())

Request

import SolarNetwork

//Mark: - GET
class HTTPBinGETRequest: SLRequest {
    
    override func loadRequest() {
        super.loadRequest()
        
        self.path = "/get"
    }
    
}

HTTPBinNetwork.request(HTTPBinGETRequest()) { (response) in
    if let dictionary = response.dataDictionary {
                        
    }
    else if let error = response.error {
        //show error
    }
}

//Mark: - POST
class HTTPBinPOSTRequest: SLRequest {
    
    override func loadRequest() {
        super.loadRequest()
        
        self.method = .post
        self.path = "/post"
    }
    
    /**
     properties will encode to parameters by Reflection
     ["userName": "myUserName",
      "password": "myPassword",
	  "name" : "youName"]
     */
    let userName = "myUserName"
    let password = "myPassword"
	
    var name: String?
}

let postReq = HTTPBinPOSTRequest()
postReq.name = "yourName"
HTTPBinNetwork.request(postReq) { (response) in
    if let dictionary = response.dataDictionary {
                        
    }
    else if let error = response.error {
        //show error
    }
}

Download

import SolarNetwork

class HTTPBinDownLoadRequest: SLDownloadRequest {
    
    override func loadRequest() {
        super.loadRequest()
        
        self.path = "/image/png"
        self.isResume = true //control the download request is resume or not, default is false
    }
}

HTTPBinNetwork.download(HTTPBinDownLoadRequest(), progressClosure: { (progress) in
                    
}) { (resposne) in
                    
}

Upload

import SolarNetwork

class HTTPBinUploadRequest: SLUploadRequest {
    
    override func loadRequest() {
        super.loadRequest()
        
        self.path = "/post"
    }
    
}

let uploadRequest = HTTPBinUploadRequest()
uploadRequest.data = data //data to upload
HTTPBinNetwork.upload(uploadRequest, progressClosure: { (progress) in
                            
}) { (response) in
                            
}

Decode

In Swift 4, you can use Codable.

import SolarNetwork

struct User: Decodable { //Swift 4 Codable
    var id: Int
    var name: String
    var token: String
}

HTTPBinNetwork.request(UserRequest()) { (response) in
    if let user = response.decode(to: User.self) {
                        
    }
    else if let error = response.error {
        //show error
    }
}

License

Alamofire is released under the MIT license. See LICENSE for details.

You might also like...
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

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

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

An elegant yet powerful iOS networking layer inspired by ActiveRecord.
An elegant yet powerful iOS networking layer inspired by ActiveRecord.

Written in Swift 5 AlamoRecord is a powerful yet simple framework that eliminates the often complex networking layer that exists between your networki

Alamofire network layer

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

Async network layer with Combine
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

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

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

VFNetwork is a protocol-oriented network layer that will help you assemble your requests in just a few steps.
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

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.

Comments
  • request.resume()无效

    request.resume()无效

    你好,目前在你的代码里发现两个问题,一个是我之前提到的没法动态更新httpHeader,还有一个是在plugin里拦截到一个错误的请求,重新设置好相应的参数,调resume方法无效,类似的代码如下:if response.apiStatus == 201630 { let loginData = LocalStorage.value(withkey: "loginInfo") as! NSDictionary let originHeader = response.request?.headers as! NSMutableDictionary originHeader.removeObject(forKey: "Authorization") originHeader.setObject((loginData["Rmem-auth"] as! NSDictionary)["value"]!, forKey: "Rmem-auth" as NSString) response.request?.headers = (originHeader as! [String : String]) response.request!.resume()},希望能帮我一下,有什么解决方案没谢谢

    opened by zhuaijunzaj 1
  • 更新httpheader

    更新httpheader

    你这个里面只能在初始化request 的时候设置header,没办法动态去更新,我现在有这样一个需求,token失效的时候,给httpheader设置另外一个参数,表示刷新token,我找了半天也没找到更新的方法,我想自己加,发现Alamofire 的Request 类里面的URLRequest 是只读,不允许修改,请问怎么解决

    opened by zhuaijunzaj 1
  • 关于 SolarNetwork 打印输出问题

    关于 SolarNetwork 打印输出问题

    SolarNetwork 打印的数据如果包含 中文 的话显示全是 Unicode 编码,

    我修改了这个方法的输出,转为 JSON 并格式化输出。 而且,建议 "data:(data ?? "")" 改为 "(data ?? "")" ,不要外加1个data: 了,因为使用者只想看到服务端返回的数据结构。 最好这个 debugDescription 方法可以加个全局控制,是否开启在 debug 模式下输出。

    extension SLResponse: CustomDebugStringConvertible {
        
        public var debugDescription: String {
            
            var dataString: String?
            
            let d = data ?? Data()
            let isJson = JSONSerialization.isValidJSONObject(d)
            if isJson {
                let jsonData = try? JSONSerialization.data(withJSONObject: d, options: [.prettyPrinted])
                let str = String(data: jsonData ?? Data(), encoding: .utf8)
                dataString = str
            }else {
                dataString = destinationURL == nil ? "data:\(data ?? "")" : "destinationURL:\(destinationURL?.absoluteString ?? "")"
            }
    
            return """
            ------------------------ SLResponse ----------------------
            URL:\(request?.URLString ?? "")
            \(dataString ?? "")
            error:\(String(describing: error))
            ----------------------------------------------------------
            
            """
        }
    
    }
    

    这是目前的:

    ------------------------ SLResponse ----------------------
    URL:http://api.jinxiansen.com/words/word
    data:{
        data =     (
        );
        message = "\U8bf7\U6c42\U6210\U529f";
        status = 0;
    }
    error:nil
    ----------------------------------------------------------
    

    这是 JSON 格式化输出后的:

    ------------------------ SLResponse ----------------------
    URL:http://api.jinxiansen.com/words/word
    {
      "message" : "请求成功",
      "status" : 0,
      "data" : [
    
      ]
    }
    error:nil
    ----------------------------------------------------------
    
    opened by NumberCode 1
Releases(5.0.0)
Owner
null
Network abstraction layer written in Swift.

Moya 15.0.0 A Chinese version of this document can be found here. You're a smart developer. You probably use Alamofire to abstract away access to URLS

Moya 14.4k Jan 4, 2023
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
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
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
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
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