AENetwork 0.9.1

AENetwork 0.9.1

tadija维护。



AENetwork 0.9.1

Swift 5 Platforms iOS | watchOS | tvOS | macOS CocoaPods Carthage Swift Package Manager License MIT

AENetwork

Swift中的简单轻量级网络

这是我为了个人使用而制作的,但您随意使用或贡献。更多示例请查看来源测试

使用方法

import AENetwork

/// - Note: Make `URL` with just a `String`
let anything: URL = "https://httpbin.org/anything"

/// - Note: Easily add parameters to `URL`
let url = anything.addingParameters(["foo" : "bar"])!

/// - Note: Factory methods on `URLRequest`
let body = try? Data(jsonWith: ["easy" : true])
let request = URLRequest.post(url: url, headers: ["hello" : "world"], body: body)

/// - Note: Convenient sending of request
request.send { result in
    if let response = try? result.get() {
        print("Status Code: \(response.statusCode)\n")
    }
}

/// - Note: Integrated `Reachability`
print("Connected to network: \(Network.isOnline)")

/// - Note: Create custom `Network` instance when needed
let network = Network()

/// - Note: Monitor reachability state changes
network.reachability.startMonitoring()
network.reachability.stateDidChange = { state in
    print("Reachability state: \(state.rawValue)\n")
}
network.reachability.stopMonitoring()

/// - Note: Send request with `Fetcher` and use `ResponseResult` in completion
network.fetcher.send(request) { (result) in
    do {
        let response = try result.get()
        print("Headers: \(response.headers as? [String : Any])\n")
    } catch {
        print(error)
    }
}

/// - Note: Simple creation of the entire backend layer
final class Backend: APIClient {
    let baseURL: URL = "https://httpbin.org"
}

/// - Note: `APIClient` will by default use shared `Network` instance for sending `APIRequest`,
/// but a custom `APIClient` implementation can do it via specific `Network` instance,
/// or even via any other way to resolve `APIRequest` and return `APIResponse` in the completion.

/// - Note: Type safe and scalable architecture of API requests
extension Backend {
    struct API {}
}
extension Backend.API {
    struct Anything: APIRequest {
        var method: URLRequest.Method { return .get }
        var path: String { return "anything" }
        var headers: [String : String]? { return ["X-Hello" : "X-World"] }
        var parameters: [String : Any]? { return ["easy" : true] }
    }
}

/// - Note: `Backend` example in action
let backend = Backend()
let apiRequest = Backend.API.Anything()

backend.send(apiRequest) { (result) in
    switch result {
    case .success(let response):
        let dictionary = try? response.toDictionary()
        print("Response: \(dictionary?.description ?? "")\n")
    case .failure(let error):
        print(error)
    }
}

安装

  • Swift包管理器:

     .package(
         url: "https://github.com/tadija/AENetwork.git",
         .upToNextMinor(from: "0.9.1")
     )
  • Carthage:

     github "tadija/AENetwork"
    
  • CocoaPods:

     pod 'AENetwork'

版权

此代码发布在MIT许可下。详情请查看LICENSE