Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 从多个视图控制器调用同一API的最佳方法是什么_Ios_Swift - Fatal编程技术网

Ios 从多个视图控制器调用同一API的最佳方法是什么

Ios 从多个视图控制器调用同一API的最佳方法是什么,ios,swift,Ios,Swift,我在一个应用程序中有20多个视图控制器。现在我从两个不同的视图控制器调用一个特定的api来从服务器获取数据。减少代码重复的最佳方法是什么?创建 class Api { static func getData(completion:@escaping:([Model]) -> ()) { // suppose you receive an array // api call here { comletion(data) } } 那么在任何vc内

我在一个应用程序中有20多个视图控制器。现在我从两个不同的视图控制器调用一个特定的api来从服务器获取数据。减少代码重复的最佳方法是什么?

创建

class Api {

  static func getData(completion:@escaping:([Model]) -> ()) { // suppose you receive an array 
     // api call here {
        comletion(data)
     }
 }
那么在任何vc内部都可以这样称呼它

Api.getData { (data) in
   print(data)
}

您可以创建一个
单例
来支持所有
API调用,如:

class APIManager {
    static let shared = APIManager()
    private init() {}

    func fetchData(with urlString: String, handler: ((Model?, Error?)->())?)  {
        //Add other params as per your requirement...
        if let url = URL(string: urlString) {
            URLSession.shared.dataTask(with: url) { (data, response, error) in
                //parse your data here...
                handler?(model, error) //model is the object you got after parsing the data..
            }.resume()
        }
    }
}
ViewController
中,您可以像这样使用它:

class VC: UIViewController {
    func fetchData() {
        APIManager.shared.fetchData(with: "YOUR_URL_STRING") { (model, error) in
            //Use model here...
        }
    }
} 
在上面的代码中,我以API调用的
URLSession
为例。您可以根据需要使用其他方式,如第三方(
Alamofire
等)