ios - 在类的每个函数中调用相同的代码

标签 ios swift alamofire uiactivityindicatorview

我有一个网络管理器类(单例)。

对于应用程序必须进行的每个 API 调用,都会调用此网络管理器中的不同函数。

我希望这个 NM 的每个函数都首先显示一个事件指示器,直到到达每个函数的完成处理程序:向用户显示正在执行请求。

最好的方法是什么?

我正在使用Alamofire pod 如果这可以帮助您。

以下是我的 API 调用之一的示例:

func loadSetting(for user: String, completionHandler: (UserSetting?) -> ()) {
    myActivityIndicator.start //a line I'd like to perform in every function of this class
    let parameters = ["UUID": user]

    _ = Alamofire.request(.POST, "http://www.google.com/users", parameters: parameters)
        .responseObject { (response: Response<UserSetting, NSError>) in
            if let userSetting = response.result.value {
                print("User Setting found remotely")
                completionHandler(userSetting)
            } else {
                print("Couldn't fetch remote User Setting")
                completionHandler(nil)
            }
            myActivityIndicator.stop //a line I'd like to perform in every function of this class
    }
}

谢谢。

最佳答案

为什么不尝试将事件指示器作为参数传递? 因此,从调用 loadSetting 函数的 View Controller 中,传入一个您持有引用的事件指示器,然后在 loadSetting 函数内启动/停止它

关于ios - 在类的每个函数中调用相同的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38535783/

相关文章:

ios - NSJSONSerialization.JSONObjectWithData 导致应用程序在 alamofire 迁移后崩溃

ios - 将数组数据模型转换为字典(swift)

ios - UINavigationBar 中的 UIBarButtonItems 不可点击

ios - tableView 数据源的字典

android - 如何在 iOS(AVFoundation 或其他第 3 方库)中使用 HLS 时移功能,如 Android 中的 ExoPlayer?

json - 为什么我不能创建 Array<[String : Any]>? Work with Alamofire (Swift)

ios - 在 Alamofire 中设置超时

ios - Swift 处理很多复杂的操作

ios - swift 3 : Understand syntax change for UITableViewDataSource method

ios - 货币复数 swift 不允许配置