我需要在收到特定错误时回忆api,说错误代码为-1005。
我想在Alamofire文件中处理这个问题,以便它可以在项目中使用所有api。
我在ObjC的AFNetworking中用 dataTaskWithHTTPMethod 处理这个问题,代码如下: -
if (failure)
{
if (error.code == -1005)
{
[self POST:URLString parameters:parameters progress:nil success:success failure:failure];
}
}
有人可以帮助我在Alamofire做这件事吗?
答案 0 :(得分:0)
//MARK: Your method
func hitYourService(){
showActivityIndicator(decision: true, inViewConroller: self, animated: true)
let deviceToken = HelpingClass.userDefaultForKey(key: "deviceToken")
let paramDict = ["email":txtFEmail.text ?? "" ,"password":txtFPassword.text ?? "" ,"device_token":deviceToken]
NetworkManager.instance().hitPostServiceJsonForm(paramDict, myReqURL: ServiceMethods.serviceBaseURL+ServiceMethods.login, unReachable: {
// Here you can handle the case if there is no internet connection
}) { (response) in
showActivityIndicator(decision: false, inViewConroller: self, animated: true)
if response != nil{
if response?["error_code"] as! Int == 0{
//Handle your response
}else{
//Show error
showHudWithMessage(message: response?["error_msg"] as! String, inViewConroller: self, animated: true, hideAfter: 2)
}
}else{
//You can hit back your service
self.hitYourService()
}
}
}
//MARK: Alamofire method to hit service, written in NetworkManager class
func hitPostServiceJsonForm(_ params:Dictionary<String,Any>, myReqURL:String, unReachable:(() -> Void),handler:@escaping ((Dictionary<String,Any>?) -> Void)) {
if networkReachable() == false {
unReachable()
}
var request = URLRequest(url: URL(string: myReqURL)!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
print_debug(object: "ReqParameter: \(String(describing: params))") // http url response
//JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
request.httpBody = try! JSONSerialization.data(withJSONObject: params, options: [])
Alamofire.request(request).responseJSON { response in
// SwiftLoader.hide()
print_debug(object: "Request: \(String(describing: response.request))") // original url request
print_debug(object: "Response: \(String(describing: response.response))") // http url response
print_debug(object: "Result: \(response.result)") // response serialization result
print_debug(object: "Result.value \(String(describing: response.result.value))")
switch response.result {
case .success:
if let jsonDict = response.result.value as? Dictionary<String,Any> {
print_debug(object: "Json Response: \(jsonDict)") // serialized json response
handler(jsonDict)
}
else{
handler(nil)
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Server Response: \(utf8Text)") // original server data as UTF8 string
}
break
case .failure(let error):
handler(nil)
print_debug(object: error)
break
}
}
}
答案 1 :(得分:0)
让我们了解一个例子。
让我猜一下,你已经创建了一个类来管理那里所有的webservice事务。 (如果还没有那么最好为最佳实践创建一个)。
现在可以创建两个 typealias 来管理响应。
这里是: -
这里我再次假设您希望整个字典用于成功响应,错误用于失败响应。
typealias successCompletion = (([String:Any]) -> ())
typealias failureCompletion = ((Error) -> ())
现在这里有一个 WSManager类,用于 处理所有与API相关的内容。
class AlamofireManager {
static func sampleFunctionOfWebService(successCompletion:successCompletion , failureCompletion:failureCompletion) {
if success {
successCompletion(["Key":"success"])
} else {
failureCompletion(-1005 as! Error)
}
}
}
你需要在函数中传递两个typealias来获取CallBack 在期望的班级。
这里只是为了理解目的,我们将传递静态 字典: - &gt; [&#34; Key&#34;:&#34; success&#34;]和static -1005 as Error。
现在如何在我们想要的课程中使用此功能?
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func wsCalling() {
AlamofireManager.sampleFunctionOfWebService(successCompletion: { (dict) in
print(dict)
}) { (error) in
if error.code == -1005 {
self.wsCalling() // recall API Again
} else {
// your other logic
}
}
}
}
我在这里没有提到过URLSeeionTask和All,这是件好事 管理URLSeeionTask。如果你有一个URLSeeionTask的实例 之前的API然后先取消它,然后再次尝试重新调用它。
快乐编码。