Ios 从多个视图控制器调用同一API的最佳方法是什么
我在一个应用程序中有20多个视图控制器。现在我从两个不同的视图控制器调用一个特定的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内
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
等)