如何检查功能是否完成?

时间:2019-08-26 22:34:43

标签: ios swift xcode

我有一个从API请求数据并将其放入全局结构的函数,因此我可以从应用程序中的任何位置读取该数据,所有其他函数和类都主要在此数据中工作。我想在运行其他类函数之前检查该函数是否已完成数据加载。

其他功能位于不同的类中。

我不能使用完成处理程序(完成:@escaping(_ success:Bool)-> Void)。因为这将在每次调用该函数时触发该函数,因此将导致一遍又一遍地下载数据。

相反,我正在寻找一种方法来检查该功能是否已完成其下载任务,然后继续其他功能。

这必须是动态的,因为如果说设备上的Internet无法正常工作,然后用户连接到Internet,则该功能将需要再次运行以尝试获取数据(可以使用刷新按钮),并通知其他类和函数再次完成操作,以便其他函数可以开始将数据加载到变量中

import Foundation 
import Alamofire 
import SwiftyJSON

struct GlobalUser {
    static var json : JSON!
     }


func getData()  {

    // set api url
    let LOCATIONAPI_URL = "https://api.darksky.net/forecast/0123456789abcdef9876543210fedcba/42.3601,-71.0589"

    // request JSON from url, using Alamofire Library

    Alamofire.request(LOCATIONAPI_URL).responseJSON { (response) in

        print("data requested")

        let result = response.result


        // check if respose is valid

        if result.isSuccess{

         GlobalUser.json = JSON(result.value!)    

     }

}

}

1 个答案:

答案 0 :(得分:1)

有时候,我遇到了this。 这个想法是有一个completionHandler,它返回

func yourFonction(_ parameters: [String: String], completionHandler: (_ result: [String: Any], _ error: Error) -> Void){
     //Your Code
     completionHandler(result, error)
}

查看here (Tutorial)here甚至there (Swift Closures Doc)以获得更多信息

相关问题