NetKit
Swift 中的简洁 HTTP 框架。
需求
NetKit 需要 Swift 5.0 和 Xcode 10.2
安装
CocoaPods
你可以使用 CocoaPods 将 NetKit 集成到你的项目中。
只需在你的 Podfile
中添加以下行
pod "NetKit"
然后在你的项目目录中运行 pod update
。
Carthage
Carthage 是一个去中心化的依赖管理器,它可以构建你的依赖并提供二进制框架。
您可以使用以下命令通过Homebrew
安装Carthage:
$ brew update
$ brew install carthage
要使用Carthage将NetKit集成到Xcode项目中,请在您的Cartfile
中指定它。
github "azizuysal/NetKit"
运行carthage update
命令来构建框架,并将构建的NetKit.framework
拖放到您的Xcode项目中。
手动方法
您可以通过将NetKit.framework
拖放到Xcode中“链接的框架和库”部分来手动将NetKit集成到项目中。
使用方法
为了运行包含的示例项目,您可以安装JSON Server。它提供了一款快速的后端用于本地机器上的原型设计和模拟。示例项目包含了db.json
文件。
使用WebService
创建特定Web服务的客户端,并使用它发送请求和处理响应。
import NetKit
let service = WebService(urlString: "https://:3000/")
service.GET("/posts")
.responseJSON { json in
print(json)
return .Success
}
.responseError { error in
print(error)
}
.resume()
responseJSON()
是一个便利的方法,它将获取响应和转换为JSON的操作合并为一部。
.response { data, response in
print(String(data: data!, encoding: NSUTF8StringEncoding))
return .Success
}
您可以从响应处理程序返回.Success
或.Failure(ErrorType)
来表示错误状态,并在出现错误的情况下将控制权传给.responseError()
。
同步请求
您可以使用resumeAndWait()
来发送同步请求。
service.PUT("/posts")
.setPath(String(post.id))
.setJSON(post.toJson())
.responseJSON { json in
print(json)
return .Success
}
.responseError { error in
print(error)
}
.resumeAndWait()
身份验证和SOAP支持
如果您需要设置额外的参数、头或身份验证处理程序,您可以通过Swift方法链来实现。
weatherService.POST()
.authenticate { (method, completionHandler) -> WebTaskResult in
switch method {
case .Default, .HTTPBasic:
completionHandler(.UseCredential, NSURLCredential(user: loginId, password: password, persistence: .ForSession))
default:
completionHandler(.PerformDefaultHandling, nil)
}
return .Success
}
.setURLParameters(["op":"GetCitiesByCountry"])
.setSOAP("<GetCitiesByCountry xmlns=\"http://www.webserviceX.NET\"><CountryName>\(country)</CountryName></GetCitiesByCountry>")
.response { data, response in
print(String(data: data!, encoding: NSUTF8StringEncoding))
return .Success
}
.responseError { error in
print(error)
}
.resume()
支持所有配置和任务类型
您可以根据短暂的或后台会话(默认为基于.defaultSessionConfiguration()
)轻松创建WebService
实例。
let service = WebService(urlString: baseURL, configuration: .ephemeralSessionConfiguration())
同样简单,您可以创建上传或下载任务(默认是数据任务)。
let task = webService.GET("resource", taskType: WebTask.TaskType.Download)
后台下载
您可以轻松设置后台URL会话并创建文件下载任务。
let webService: WebService = {
let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("com.azizuysal.netkit.test")
configuration.requestCachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
let service = WebService(urlString: baseURL, configuration: configuration)
return service
}()
您可以使用方便的文件下载处理器 responseFile()
来处理下载的文件。
downloadService.getFile()
.responseFile { (url, response) in
let path = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first?
if let url = url, response = response, filename = response.suggestedFilename, path = path?.URLByAppendingPathComponent(filename) {
do {
try NSFileManager.defaultManager().copyItemAtURL(url, toURL: path)
} catch let error as NSError {
print(error.localizedDescription)
return .Failure(error)
}
} else {
return .Failure(WebServiceError.BadData("Bad params"))
}
notifyUser(DownloadService.FileDownloaded, filename: response?.suggestedFilename)
return .Success
}.responseError { error in
print((error as NSError).localizedDescription)
notifyUser(DownloadService.FileDownloaded, error: error)
}
.resumeAndWait()
##许可证
MIT许可证 (MIT)