测试已测试 | ✗ |
语言语言 | SwiftSwift |
许可证 | Apache 2 |
发布上次发布 | 2019年3月 |
SPM支持 SPM | ✗ |
由Edison Santiago维护。
依赖项 | |
SwiftHTTP | >= 0 |
Locksmith | >= 0 |
PKHUD | >= 0 |
Neorequest 是围绕 SwiftHTTP 的一个简单包装,提供了一些额外的功能,通过解耦错误和成功处理,提供了一个更简洁的语法。
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
。如果未传递配置对象,则会创建一个具有以下默认值的对象。
loadingType: NeorequestLoadingType
:一个枚举,表示是否应该在请求期间在期望的视图中显示加载。您可以显示一个 fullScreen
加载或一个 overScreen
加载,具体如下所示。默认值是 none,除非指定,否则不会显示任何加载。fullScreen(loadingViewController: UIViewController, loadingIconColor: UIColor?)
:在所有 UIViewController
视图之上创建一个叠加视图,背景颜色与 viewController.view
相同,并有一个居中的 UIActivityIndicatorView
和所需的颜色。overScreen
:当设置为此模式时,我们依赖于PKHUD在应用程序整个范围内显示加载。由于 PKHUD
使用 UIWindow
,因此不需要对 UIViewController
的引用来显示加载。numberOfRetries: Int
:请求在调用错误处理器之前应该失败多少次。默认值:1isJsonRequest: Bool
:指定请求必须不以json格式发送。如果设置为false,则将请求作为x-www-form-urlencoded发送(但响应始终按json处理)。默认值:trueprogress: ((Float) -> Void)?
:用于在原始请求上设置进度闭包。有关更多信息,请参阅SwiftHTTP文档。默认值:nilonOperationCreated: ((HTTP) -> Void)?
:创建后调用闭包,以原生的Operation对象为参数,如果您想使用 NSOperationQueue
。默认值:niljsonDecoderConfigurationHandler: ((JSONDecoder) -> JSONDecoder)
:用于配置 Swift Decodable
协议使用的解码器的闭包。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
}
)
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
数据在默认情况下用于所有保存值后的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.beareraccount: String?, password: String?
:仅保存一次认证信息,以便您可以在生成令牌的过程中随时检索它。默认值:niltokenString: String? | tokenExpirationDate: Date? | tokenUsageTime: TimeInterval
:管理令牌的再生。令牌仅在需要时再生,在 .bearer
模式下,该类会自动管理并知道何时再生令牌。默认的 tokenUsageTime 是 1800。虽然 NeorequestAuthorization
自动管理了很多东西,但如果你使用 .bearer
或 .custom
身份验证,你需要使用一些特定逻辑设置一些闭包来完成你的应用。
NeorequestAuthorization.regenerateBearerTokenHandler
((NeorequestAuthorization, onError: ((NeorequestError) -> Void), onSuccess: (() -> Void)) -> Void)
NeorequestAuthorization
对象包含了之前保存的所有信息,因此你现在可以获取它们。请记住,此方法可以在其他请求期间被调用,因此始终调用收到的闭包 onError
和 onSuccess
以确保其他请求可以继续。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
来获取另一个令牌。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 文件。