此库 Sio
受影响于 Dio
,这是最常用的 http 客户端库之一。 Dio
具有很多非常有用的 http 连接功能。 Sio 从 Dio
中挑选了一些有用的功能,并以 URLSession
的包装器形式实现,该库也处理 http 连接。
要添加此包,您可以按照以下步骤操作
- 打开 Xcode
- 在 Mac 的导航栏中点击
添加包依赖...
。 - 在右上角的搜索框中输入
https://github.com/Kate941-su/Sio
。
欢迎使用 Sio!
var sio = Sio()
/// You can define a base URI. Once you define a baseURI, you can focus
/// on the location path
sio.baseOptions.baseURI = URL(string: "http://127.0.0.1:8000/")
let response: Response = try await sio.get(path: "api/get/json")
let dict:[String: Any] = response.json
var sio = Sio()
let data: [String: Any] = ["name": "Kate941-su", "age" : 26]
sio.baseOptions.baseURI = URL(string: "http://127.0.0.1:8000/")
let response = try await sio.post(path: "api/post/json", data: data)
! 此功能只能在 iOS 15.0 及以上版本中使用。
var sio = Sio()
if #available(iOS 15.0, *) {
var sio = Sio()
sio.baseOptions.baseURI = URL(string: "http://127.0.0.1:8000")
let (filePath, response) = try await sio.download(path: "/api/get/download/video")
}
您可以通过使用 xxxUri()
方法直接将 URI
放入。
sio.baseOptions.requestHeader = [
RequestHeader(headerField: "Content-Type", headerValue: "application/json")
]
let response = try await sio.postUri(uri: URL(string: "http://127.0.0.1:8000/api/post/uri/json")!)
您也可以使用 postUri()
和 downloadUri
如果您只想使用一个实例,建议在项目中使用
Sio
的单例以避免未知错误。
Sio
有一个基本选项。
var sio = Sio()
sio.baseOptions.baseUri = "https://api.cocoapods.org"
sio.baseOptions.mimyType = "applicationJson"
sio.baseOptions.queryParameters = ["test1" : "1", "test2" : "2"]
sio.baseOptions.timeout = 5.0
当您在 options
参数中设置一个选项时,您可以覆盖 options
。
优先级
- 在 http 方法中设置的选项。
- 在 sio 实例中设置的选项。
! RequestOptions 和 BaseOptions 具有相同的参数和采用相同的协议。但是将来,它们将具有不同的参数(RequestOptions 将具有其他参数)。但是您可以在 options
参数中设置它们。
var sio = Sio()
let requestOptions: RequestOptions = RequestOptions(timeout: 3.0)
let response: Response = try await sio.get(path: "api/get/json", options: requestOptions)
API 的基本 http 连接是
func request(
uri: URL,
options: OptionProtcol,
requestMethod: RequestMethod,
onSendProgress: ProgressCallback? = nil,
onReceiveProgress: ProgressCallback? = nil
) async throws -> Response
public class Response{
// The data of response body
let data: Data
// This feature is implementes in the future
let statusCode: StatusCode
let mimeType: String
let date: Date?
let contentLength: Int
// You can get raw http response data.
// Now, you can extract statusCode
// in the header structed by json type
let respnseHeader: URLResponse
}
如果您成功获取到响应,可以将其转换为 swift 类型。
let response = try await sio.postUri(uri: URL(string: "http://127.0.0.1:8000/api/post/uri/json")!)
let map: [String: Any] = response.json
let text: String = response.text
// let data = response.data : default
当发生错误时,Sio 将将 Error
包装到 SioError
// 获取 404 do { let response = try await sio.get(path: "api/get/json") } catch { print(error.message) // 404 - Not Found print(error.statusCode) // StatusCode.not_found }
如果您觉得使用这个库感觉很好,并且想让它变得更好,请随意提交 issue 和 comment。