在 iOS 中调用多个服务的更好方法是什么?

kir*_*ran 5 request ios swift alamofire

我有 5 个不同的服务请求加载到每个单元格的相同 UItableView 中。

为了做到这一点,最好的方法是什么?

https://example.com/?api/service1
https://example.com/?api/service2
https://example.com/?api/service3
https://example.com/?api/service4
https://example.com/?api/service5

let url = "https://example.com/?api/service1
Alamofire.request(url, method: .get, parameters:nil encoding: JSONEncoding.default, headers: nil)
    .responseJSON { response in
        print(response.result.value as Any)   // result of response serialization
}
Run Code Online (Sandbox Code Playgroud)

使用不同的服务名称重复相同的 Alamofire 五次还有另一种方法来实现它。

Scr*_*ble 3

查看使用DispatchGroup执行多个异步请求并等待它们全部完成。

对于您调用的每个任务group.enter(),以及在其完成处理程序中,当您知道请求已完成时,您可以调用group.leave(). 然后有一个通知方法,它将等待所有请求调用leave,告诉您它们已全部完成。

我在 Playground 中创建了一个示例(由于使用了 URL,该示例将失败并出现错误)

import UIKit
import PlaygroundSupport

let serviceLinks = [
    "https://example.com/?api/service1",
    "https://example.com/?api/service2",
    "https://example.com/?api/service3",
    "https://example.com/?api/service4",
    "https://example.com/?api/service5"
]

// utility as I've not got alamofire setup
func get(to urlString: String, completion: @escaping (Data?, URLResponse?, Error?) -> Void) {
    let url = URL(string: urlString)!
    let session = URLSession.shared
    let task = session.dataTask(with: url) { data, response, error in
        completion(data, response, error)
    }
    task.resume()
}

let group = DispatchGroup()

for link in serviceLinks {
    group.enter() // add an item to the list 
    get(to: link) { data, response, error in
        // handle the response, process data, assign to property
        print(data, response, error)
        group.leave() // tell the group your finished with this one
    }
}

group.notify(queue: .main) {
    //all requests are done, data should be set
    print("all done")
}

PlaygroundPage.current.needsIndefiniteExecution = true
Run Code Online (Sandbox Code Playgroud)

您可能无法像我一样循环访问 URL,因为每个服务的处理可能不同。您需要根据您的需要对其进行调整。

有很多关于DispatchGroups在线可用的信息,例如这篇文章