所以我正在关注一个用于处理网络请求的 git 存储库。我已经成功地将它实现到我的应用程序中,followed guide .
我在我的 SignInController
中调用 SignInOperation
:SignInOperation(email: email, password: password).start()
因此,此 repo 的设置方式主要是处理 RequestOperation 中的成功和失败,如下所示:
import Foundation
public class SignInOperation: ServiceOperation {
private let request: SignInRequest
public var success: ((SignInItem) -> Void)?
public var failure: ((NSError) -> Void)?
public init(email: String, password: String, service: BackendService = MyBackendService(BackendConfiguration.shared)) {
request = SignInRequest(email: email, password: password)
super.init(service: service)
}
public override func start() {
super.start()
service.request(request, success: handleSuccess, failure: handleFailure)
}
private func handleSuccess(_ response: Any?) {
do {
let item = try SignInResponseMapper.process(response)
self.success?(item)
self.finish()
} catch {
handleFailure(NSError.cannotParseResponse())
}
}
private func handleFailure(_ error: NSError) {
self.failure?(error)
self.finish()
}
}
主要是我想做的是:
SignInOperation(email: email, password: password).start().then(
// handleResponse
)
甚至不一定是那样。但这只是我可以处理 Controller 中的响应而不是网络文件的一种方式。任何建议或想法将不胜感激。如果有人觉得有必要,我绝对可以分享更多代码。
附言。我特别尝试遵循这种处理您的 Network Requests
的设计,因为我正在构建一个更大规模的社交应用程序。因此,我想要可维护、可扩展和可测试的东西。
最佳答案
操作成功和错误状态被传递给闭包调用闭包来处理。希望下面的代码对您有所帮助。
class Test : UIViewController{
let mail = "abc@xyz.com"
let password = "******"
var operation : SignInOperation?
override func viewDidLoad() {
super.viewDidLoad()
operation = SignInOperation(email: mail, password: password)
operation?.failure = { error in
print(error.localizedDescription)
// handle failure over here
}
operation?.success = { item in
// handle success here
// you can use data from item which is an Instance of SignInItem over here
}
}
}
关于iOS Swift 网络层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51756235/