Neorequest 2.7.0

Neorequest 2.7.0

测试已测试
语言语言 SwiftSwift
许可证 Apache 2
发布上次发布2019年3月
SPM支持 SPM

Edison Santiago维护。



 
依赖项
SwiftHTTP>= 0
Locksmith>= 0
PKHUD>= 0
 

  • 作者
  • Neomode

Neorequest

Neorequest 是围绕 SwiftHTTP 的一个简单包装,提供了一些额外的功能,通过解耦错误和成功处理,提供了一个更简洁的语法。

特性

  • 更简洁的语法,单独的闭包来管理请求的成功和错误
  • 支持 Swift Decodable 协议
  • 请求授权管理
  • 视图上加载指示器的管理

安装

CocoaPods

Neorequest 通过CocoaPods 提供。只需在您的 Podfile 中添加 pod 'Neorequest' 并运行 pod install

入门

创建一个简单的请求

所有响应都会自动解析为对象,使用的是 'Decodable' 协议。使用 Neorequest 发起请求非常简单

Neorequest<Object>.GET(
	url: "https://yoururl.com",
	onError: {
		error in
		//Handle request error here
	},
	onSuccess: {
		obj in
		//Handle success response here
	}
)

发送参数

您可以将任何数据以 Dictionary<String: Any> 的形式传递给 parameters 属性。

Neorequest<Object>.POST(
    url: "https://yoururl.com",
    parameters: ["name": "John Doe", "age": 7],
    onError: {
        error in
        //Handle request error here
    },
    onSuccess: {
        obj in
        //Handle success response here
    }
)

对于上传文件,您可以参考 Swift HTTP 上传 并将 Upload 对象作为参数传递。要了解如何发送 x-www-form-urlencoded 请求,请参阅此文件中的 NeorequestConfiguration 部分。

读取响应

onSuccess((T) -> Void) 接收调用中指定的解析对象。所有对象都是使用 Decodable 协议创建的,因此请确保您符合该协议。
如果响应是空对象({})或空响应,您可以为泛型参数提供一个空对象。为了方便,Neorequest 提供了一个 box 的 NeorequestEmptyResponse

关于配置 JSONDecoder 的详细信息,请参阅本文件中的 NeorequestConfiguration 部分,以设置 dateFormat 及其他选项。

您可以像使用任何字典一样检索响应值

Neorequest<Object>.GET(
    url: "https://yoururl.com",
    onError: {
        error in
        //Handle request error here
    },
    onSuccess: {
        obj in
        //The object is already created an ready for use. No need to parsing.
        print(obj.name)
    }
)

请注意,响应始终使用 Swift 4 Decodable 协议解析到对象。如果在解析过程中抛出错误,则 onError((Error) -> Void) 闭包将使用错误 NeorequestError.ParseError(content: String?) 调用,其中 content 是将原始 Data 转换为 UTF8 String

Neorequest 支持第一级上的数组。由于 Swift 4 Decodable 使 Decodable 符合的数组默认符合 Decodable,因此您只需将数组作为调用的参数传递即可。请注意,单个对象不能转换为数组,反之亦然,因此传递错误类型会导致解析错误。

Neorequest<[Object]>.GET(
    url: "https://yoururl.com",
    onError: {
        error in
        //Handle request error here
    },
    onSuccess: {
        objects in
        for object in objects {
            //Do something with the objects of the array
            print(object.name)
        }
    }
)

全局头

如果您必须将自定义 HTTP 标头包含在您的应用程序中发出的所有请求中,您只需将其添加到 Neorequest.globalHeaders: [String:String]

import Neorequest

//The globalHeaders are saved on NSUserDefaults, so you must retrieve the array to edit it
var globalHeaders = Neorequest<Object>.globalHeaders
globalHeaders["Header"] = "Value"
Neorequest<Object>.globalHeaders = globalHeaders

请勿在使用NeorequestAuthorization时在此处设置Authorization HTTP头部。

NeorequestConfiguration

NeorequestConfiguration 结构体允许您设置请求的一些特定配置。我们将这些参数放在独立的结构体中,以便主请求调用不会因为不会经常使用的参数而变得臃肿。

请注意,所有请求都有一个关联的NeorequestConfiguration如果未传递配置对象,则会创建一个具有以下默认值的对象。

NeorequestConfiguration 属性

  • loadingType: NeorequestLoadingType:一个枚举,表示是否应该在请求期间在期望的视图中显示加载。您可以显示一个 fullScreen 加载或一个 overScreen 加载,具体如下所示。默认值是 none,除非指定,否则不会显示任何加载。
    • fullScreen(loadingViewController: UIViewController, loadingIconColor: UIColor?):在所有 UIViewController 视图之上创建一个叠加视图,背景颜色与 viewController.view 相同,并有一个居中的 UIActivityIndicatorView 和所需的颜色。
    • overScreen:当设置为此模式时,我们依赖于PKHUD在应用程序整个范围内显示加载。由于 PKHUD 使用 UIWindow,因此不需要对 UIViewController 的引用来显示加载。
  • numberOfRetries: Int:请求在调用错误处理器之前应该失败多少次。默认值:1
  • isJsonRequest: Bool:指定请求必须不以json格式发送。如果设置为false,则将请求作为x-www-form-urlencoded发送(但响应始终按json处理)。默认值:true
  • progress: ((Float) -> Void)?:用于在原始请求上设置进度闭包。有关更多信息,请参阅SwiftHTTP文档。默认值:nil
  • onOperationCreated: ((HTTP) -> Void)?:创建后调用闭包,以原生的Operation对象为参数,如果您想使用 NSOperationQueue。默认值:nil
  • jsonDecoderConfigurationHandler: ((JSONDecoder) -> JSONDecoder):用于配置 Swift Decodable 协议使用的解码器的闭包。

NeorequestConfiguration 示例

  • 在执行请求时显示整个视图的灰色加载
import Neorequest

var config = NeorequestConfiguration()
config.loadingType = .fullScreen(
    loadingViewController: myViewController,
    loadingIconColor: UIColor.lightGray
)

Neorequest<Object>.GET(
    url: "https://yoururl.com",
    configuration: config,
    onError: {
        error in
        //Handle request error here
    },
    onSuccess: {
        obj in
        //Handle success response here
    }
)
  • 发送表单数据请求,重试10次,并在请求过程中显示叠加加载
import Neorequest

var config = NeorequestConfiguration()
config.isJsonRequest = false
config.numberOfRetries = 10
config.loadingType = .overScreen

Neorequest<Object>.GET(
    url: "https://yoururl.com",
    configuration: config,
    onError: {
        error in
        //Handle request error here
    },
    onSuccess: {
        obj in
        //Handle success response here
    }
)
  • 使用自定义日期格式解析日期
import Neorequest

var config = NeorequestConfiguration()
config.jsonDecoderConfigurationHandler = {
    decoder in
    let dateFmt = DateFormatter()
    dateFmt.locale = Locale.current
    dateFmt.timeZone = TimeZone(identifier: "UTC")
    dateFmt.dateFormat = "yyyy-MM-dd'T'HH:mm"
    decoder.dateDecodingStrategy = .formatted(dateFmt)
    return decoder
}

Neorequest<Object>.GET(
    url: "https://yoururl.com",
    configuration: config,
    onError: {
        error in
        //Handle request error here
    },
    onSuccess: {
        obj in
        //Handle success response here
    }
)

NeorequestAuthorization

NeorequestAuthorization 是一个单例类,它提供了一种简单的方式来管理整个应用程序中所有请求的授权。它为您处理令牌过期和再生,所以您不需要在发出请求之前担心令牌是否有效。如果需要,它们将在请求继续之前再生。
NeorequestAuthorization 数据在默认情况下用于所有保存值后的HTTP请求。如果您需要在必须不使用授权的调用中(例如,身份验证请求),您可以在请求调用上指定authorization: nil

Neorequest<Object>.POST(
    url: "https://yoururl.com",
    authorization: nil,
    parameters: ["name": "John Doe", "age": 7],
    onError: {
        error in
        //Handle request error here
    },
    onSuccess: {
        obj in
        //Handle success response here
    }
)

属性

NeorequestAuthorization 有一些属性来保存用于授权的值。所有数据都仅使用Locksmith保存在iOS Keychain中,以确保用户敏感信息的安全。

  • authType:我们支持 Bearer 授权、基本授权,还支持一种自定义授权方法,其中您必须提供令牌字符串的生成。默认值:NeorequestAuthorizationType.bearer
  • account: String?, password: String?:仅保存一次认证信息,以便您可以在生成令牌的过程中随时检索它。默认值:nil
  • tokenString: String? | tokenExpirationDate: Date? | tokenUsageTime: TimeInterval:管理令牌的再生。令牌仅在需要时再生,在 .bearer 模式下,该类会自动管理并知道何时再生令牌。默认的 tokenUsageTime1800

闭包

虽然 NeorequestAuthorization 自动管理了很多东西,但如果你使用 .bearer.custom 身份验证,你需要使用一些特定逻辑设置一些闭包来完成你的应用。

Bearer 身份验证

  • NeorequestAuthorization.regenerateBearerTokenHandler((NeorequestAuthorization, onError: ((NeorequestError) -> Void), onSuccess: (() -> Void)) -> Void)
    • 这个闭包负责在需要时(再次)生成令牌并检查是否成功。如果已经设置了用户数据,那么作为参数传入的 NeorequestAuthorization 对象包含了之前保存的所有信息,因此你现在可以获取它们。请记住,此方法可以在其他请求期间被调用,因此始终调用收到的闭包 onErroronSuccess 以确保其他请求可以继续。
    • 由于令牌总是在远程API返回 401 Неавторизован 时再生,因此如果在使用无效的身份验证数据尝试发出请求时,可能会陷入循环。因为这个原因,用户数据将不会自动保存,你应该在你确信凭证有效的时调用 .save()。在用户数据被保存并生成令牌后,你不再需要担心这个问题,一切都将为你处理。
    • 在你使用 bearer 模式发出任何请求之前,这个闭包必须被设置,所以我们建议在应用程序初始化时设置它。

自定义身份验证

  • NeorequestAuthorization.regenerateCustomTokenHandler((NeorequestAuthorization, @escaping ((NeorequestError) -> Void), @escaping (() -> Void)) -> Void)

    • 这与 regenerateBearerTokenHandler 有相同的功能。请参阅上面关于此闭包的解释以获得更多详细信息。
  • NeorequestAuthorization.getCustomValidAuthHeaderStringHandler((NeorequestAuthorization, @escaping ((NeorequestError) -> Void), @escaping ((String) -> Void)) -> Void)

    • 使用此方法提供用于字符串 Authorization 标头的有效字符串。由于你正在使用自定义验证,所以我们无法为你执行此操作。
    • 在此处理程序中,你应该验证是否必须使用 NeorequestAuthorization 的参数更新令牌,或者保存的令牌是否仍然有效。如果有必要,你可以调用 .regenerateCustomTokenHandler 来获取另一个令牌。
    • 你应该将 Authorization HTTP 标头 的值传递给 onSuccess 闭包。如果你需要在标头中添加任何固定值,请在这里进行。

保存和删除用户数据

保存新数据

创建一个新的 NeorequestAuthorization 实例,设置所需的属性并再生令牌。你提供的 regenerateBearerTokenHandler 必须保存新值。请注意,保存新数据将 覆盖任何现有数据,因为我们仍然不支持处理多个账户。

let auth = NeorequestAuthorization()
auth.account = "account"
auth.password = "password"
auth.regenerateBearerToken(
    onError: {
        error in
        //Manage the error
    },
    onSuccess: {
        //User authenticated and token regenerated
    }
)

检索保存的数据

NeorequestAuthorization.load() 将返回一个对象,该对象包含从密钥链初始化的所有信息,如果存在,否则返回 nil。

强制令牌再生

如果由于某些原因你必须在下一个请求上强制令牌再生,你可以对一个填充的对象调用 expirateToken,这将使令牌过期,并在下一个请求中更新它。要立即再生令牌,可以使用 regenerateBearerToken(onError: ((NeorequestError) -> Void), onSuccess: () -> Void)

删除现有数据

NeorequestAuthorization.load()?.delete() 将删除任何现有数据。

示例

在应用程序初始化时设置令牌再生处理程序

import Neorequest

NeorequestAuthorization.regenerateBearerTokenHandler = {
    auth, onError, onSuccess in

    //The remote api authentication endpoint uses x-www-form-url-encoded
    var config = NeorequestConfiguration()
    config.isJsonRequest = false

    Neorequest<TokenObject>.POST(
        url: "http://yoururl.com/auth",
        authorization: nil,
        parameters: ["account": auth.account, "password": auth.password],
        configuration: config,
        onError: onError, //Use the provided error handler to return to the original request
        onSuccess: {
            tokenObj in
            //Retrieve the token and save it
            auth.tokenString = "..."

            //Since the request is valid we can save the auth data now
            auth.save()

            //Proceed with the request
            onSuccess()
        }
    )
}

首次为用户登录并保存其数据

import Neorequest

let auth = NeorequestAuthorization()
auth.account = account
auth.password = password
auth.regenerateBearerToken(
    onError: {
        error in
        //Problem regenerating the token. Maybe the user provided bad credentials?
    },
    onSuccess: {
        //Token regenerated. Proceed with the next requests
    }
)

许可证

Neorequest 采用 Apache v2 许可证。有关更多信息,请参阅 LICENSE 文件。