如何为Alamofire响应设置委托

时间:2018-06-21 06:40:07

标签: ios swift

我是IOS的新手。我正在使用Alamofire发出网络请求。我在追踪...方面非常成功。

  1. 使用参数进行请求
  2. 显示活动指示器
  3. 获取响应并隐藏活动指示器
  4. 将响应解析为模式

我对OOP有很好的理解。而且我在android中有很好的工作经验。在android中,我使用了一个用于服务的集中式类,并从活动中调用它,然后使用回调传递了结果。

这样,它更加紧凑,避免了我一次又一次地编写相同的代码。我对其进行搜索,发现委托与java / android中的Callbacks / Interfaces相同。

我的问题:

  

谁能告诉我如何在一堂课中编写Alamofire代码,以及如何   从其他视图控制器用不同的号码调用   参数类型。并以不同类型的结果发送回   进入相关的View控制器? 迅速可以使用吗?

4 个答案:

答案 0 :(得分:2)

使用WebServicesCall或您的首选名称创建一个快捷文件,并使用以下代码。这里我正在使用SwiftyJSONAlamofire

import UIKit
import Alamofire
import SwiftyJSON

struct WebService {
static func requestService(url: URL, method: HTTPMethod, parameters: Parameters, headers: HTTPHeaders? = nil, showLoaderFlag: Bool, viewController: UIViewController, completion: @escaping (_ success: JSON) -> Void) {
        /* check for internet connection */
        if(Reachability.isConnectedToNetwork()) {
            /* Show Loader here */

            print("Web Service - \(url)")
            print("Header - \(String(describing: headers))")
            print("Parameters - \(parameters)")

            /* Request configure */
            AlmofireService.Manager.request(url, method: method, parameters: parameters, encoding: JSONEncoding.default, headers: header) .responseJSON { response in
                print("Response - \(response)")

                switch response.result {
                case .success(_):
                    /* Hide loader here */

                    let json = JSON(response.result.value!)

                    completion(json)

                case .failure(_):
                    print("Request failed with error: \(response.result.error ?? "" as! Error)")

                    if response.result.error?._code == NSURLErrorTimedOut {
                        //TODO: show response time out alert or message here
                    } else {
                        //TODO: show response failure alert or message here
                    }

                    /* Hide loader here */

                    completion(JSON.null)
                }
            }
        } else {
            print("No internet connection")

            //TODO: show no internet connection alert or message here

            let json: JSON = ["status": "nointernet",
                          "code": 503]
            completion(json)
        }
    }
    }

然后在需要时致电如下

func callWebService() {
        let parameters: [String: Any] = ["key": "value"] //for post request
        let headers: [String: String] = ["key": "value"]
        let url = //your url here

        WebService.requestService(url: url, method: .post, parameters: parameters, headers: headers, showLoaderFlag: true, viewController: self, completion: { response in

            guard response["code"].int != 503 else {
                print("No internet connection")
                return
            }

            guard response != .null else {
                return
            }

            /* Handle your success response here */

        })
    }

答案 1 :(得分:1)

创建一个NSObject类,并在其中创建一个类级别的函数。并从其他任何班级中调用它

import Alamofire

class Network: NSObject {

class func API_PostData(_ strURL: String, parameter Params: NSDictionary, successWithStatus1Closure: @escaping (AnyObject?) -> (), successWithStatus0Closure: @escaping (AnyObject?) -> (), failurClosure: @escaping (String?)-> ())
    {

        let Param: [String: Any] = Params.mutableCopy() as! [String : Any]


        let complite_url = BASE_URL+strURL


        if Reachability.isConnectedToNetwork(){



            Alamofire.request(complite_url, method: .post, parameters: Param ,encoding: JSONEncoding.default).responseJSON {
                response in
                if(response.result.error != nil)
                {
                    let error = response.result.error
                    if (error?.localizedDescription == "The request timed out."){
                        failurClosure("The request timed out.");
                        return
                    }
                    if (error?.localizedDescription == "Could not connect to the server."){
                        failurClosure("Could not connect to the server.");
                        return
                    }
                    if (error?.localizedDescription == "The network connection was lost."){
                        failurClosure("The network connection was lost.");
                        return
                    }
                }
                let dictResponse = response.result.value as? NSDictionary

                print("Response",response)

                if dictResponse is Dictionary<AnyHashable,Any> {
                    print("Yes, it's a Dictionary")
                }
                else{
                    print("No, it's a not a Dictionary")
                    failurClosure("Active internet connection required")
                    return
                }

                let isSuccess = dictResponse!["success"] as! Int

                if isSuccess == 1
                {
                    successWithStatus1Closure(dictResponse)
                }else{
                    successWithStatus0Closure(dictResponse)
                }

            }
        }else {

            print("Active internet connection required");
            failurClosure("Active internet connection required")
            return
        }

    }
    }

并像

一样使用它
Network.API_PostData

和xCode将自动完成该方法

在您的视图控制器中使用示例创建方法

func callApi(){
    let para = ["user_id" : USER_ID_STR,
                "page" : String(page),
                "item_per_page" : "15"
        ] as NSDictionary
    SVProgressHUD.show()
    GlobalClass.API_PostData("notifications/activities", parameter: para, successWithStatus1Closure: { (response) in

        print("response \(response)")
        SVProgressHUD.dismiss()
    }, successWithStatus0Closure:{ (response) in
        print("response \(response)")
        SVProgressHUD.dismiss()
    }, failurClosure: { (error) in
        print("error \(error ?? "ddd")")
        GlobalClass.showAlert(alertTitle: "", alertMsg: error!, view: self)
        SVProgressHUD.dismiss()
    })
}

并像

那样称呼它
callApi()

答案 2 :(得分:0)

您可以通过编写回调方法或关闭来满足您的要求。例如:

func yourMethodName(completion:@escaping (YourModelClass) -> Void,onError:@escaping (Error) -> Void) {
    let dataRequest = RequestObject()
    dataRequest.apiURL = YourApiURl
    dataRequest.headers = DesiredHeaders
    dataRequest.requestType = RequestType

    //This will be your method for the webservice call, whenever you get success or error, return a callback to the calling class via completion.
    NetworkManager.getDataFor(Request: dataRequest, success: {response in
        //print(response.responseObject!)
        let model = YourModelClass.init(WithDictionary: response.responseObject as? [String : Any])
        completion(model)
    }, failure: {error in
        onError(error)
  })
}

希望这会有所帮助。 对于任何查询,请随时发表评论。

答案 3 :(得分:0)

尝试一下

快速

在WebService类中:发布通知

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "yourNotificationName"), object: nil)

在您要接收响应的类中:首先注册该通知,然后编写处理该通知的方法。 您将相应的选择器赋予该方法。 //视图确实加载

NotificationCenter.default.addObserver(self, selector: #selector(yourClass.handleUpdatedData), name: NSNotification.Name(rawValue: "yourNotificatioName"), object: nil)

-(void)handleUpdatedData:(NSNotification *)notification {
    NSLog(@"recieved");
    [self.tableView reloadData];
}

目标C ...

在WebService类中:发布通知

[[NSNotificationCenter defaultCenter] postNotificationName:@"DataUpdated"
                                                        object:self];

在您要接收响应的类中:首先注册该通知,然后编写处理该通知的方法。 您将相应的选择器赋予该方法。 //视图确实加载

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(handleUpdatedData:)
                                             name:@"DataUpdated"
                                           object:nil];

-(void)handleUpdatedData:(NSNotification *)notification {
    NSLog(@"recieved");
    [self.tableView reloadData];
}