[英]Making multiple map local searches synchronously
我嘗試同步進行多個搜索(我的意思是一個接一個,在運行下一個之前等待上一個請求完成)並阻塞直到所有操作完成后再繼續。
但是一旦信號量放棄,本地搜索的完成句柄看起來就被阻塞並運行。 我做了很多嘗試都沒有成功。
我的代碼和日志如下(可以復制/粘貼到playground):
import CoreLocation
import MapKit
func search(_ query: String, in span: MKCoordinateSpan, centered center: CLLocationCoordinate2D, id: Int) {
let semaphore = DispatchSemaphore(value: 0)
//let group = DispatchGroup(); group.enter()
// Run the request for this rect
print("\(#function): local search on the \(id)th portion ")
let request = MKLocalSearch.Request()
request.naturalLanguageQuery = query
request.region = MKCoordinateRegion(center: center, span: span)
if #available(iOS 13, *) {
request.resultTypes = .pointOfInterest
}
let search = MKLocalSearch(request: request)
search.start { response, error in
print("\(id) got \(response?.mapItems.count) items")
semaphore.signal()
}
let s = semaphore
//let s = group
// Wait for the request ot complete
print("\(#function): waiting for the \(id)th portion to complete")
//guard _ = s.wait(wallTimeout: .distantFuture) else {
guard s.wait(timeout: .now() + 5) == .success else {
print("\(#function): ***Warning: \(id)th timeout, job incomplete")
return
}
print("\(#function): \(id)th completed")
}
let rect = CGRect(
x: 48.10,
y: 3.43,
width: 0.09,
height: 0.09
)
let n = 4
let latDelta = rect.width / CGFloat(n)
var latOffs = rect.minX
let queue = OperationQueue()
//queue.maxConcurrentOperationCount = 1
var ops = [BlockOperation]()
// -- Run all asyn loca search requests synchronuously
for i in 0..<n {
// Take the next cut of the original region
let portion = CGRect(
x: latOffs,
y: rect.minY,
width: latDelta,
height: rect.height
)
latOffs += latDelta
ops.append(BlockOperation { [portion, i] in
let center = CLLocationCoordinate2D(latitude: CLLocationDegrees(portion.midX), longitude: CLLocationDegrees(portion.midY))
let span = MKCoordinateSpan(latitudeDelta: CLLocationDegrees(portion.width), longitudeDelta: CLLocationDegrees(portion.height))
search("coffee", in: span, centered: center, id: i)
})
}
queue.addOperations(ops, waitUntilFinished: true)
print("All done")
當前的虛假輸出:
search(_:in:centered:id:): local search on the 1th portion
search(_:in:centered:id:): local search on the 2th portion
search(_:in:centered:id:): local search on the 3th portion
search(_:in:centered:id:): local search on the 0th portion
search(_:in:centered:id:): waiting for the 1th portion to complete
search(_:in:centered:id:): waiting for the 3th portion to complete
search(_:in:centered:id:): waiting for the 2th portion to complete
search(_:in:centered:id:): waiting for the 0th portion to complete
search(_:in:centered:id:): ***Warning: 0th timeout, job incomplete
search(_:in:centered:id:): ***Warning: 2th timeout, job incomplete
search(_:in:centered:id:): ***Warning: 1th timeout, job incomplete
search(_:in:centered:id:): ***Warning: 3th timeout, job incomplete
All done
0 got Optional(10) items
2 got Optional(10) items
1 got Optional(10) items
3 got Optional(10) items
[更新]
預期的輸出應該顯示 no ***Warning
和All done
作為最后一行,如下(編號的確切順序取決於網絡條件):
search(_:in:centered:id:): local search on the 1th portion
search(_:in:centered:id:): local search on the 2th portion
search(_:in:centered:id:): local search on the 3th portion
search(_:in:centered:id:): local search on the 0th portion
search(_:in:centered:id:): waiting for the 1th portion to complete
search(_:in:centered:id:): waiting for the 3th portion to complete
search(_:in:centered:id:): waiting for the 2th portion to complete
search(_:in:centered:id:): waiting for the 0th portion to complete
0 got Optional(10) items
search(_:in:centered:id:): 0th completed
2 got Optional(10) items
search(_:in:centered:id:): 2th completed
1 got Optional(10) items
search(_:in:centered:id:): 1th completed
3 got Optional(10) items
search(_:in:centered:id:): 3th completed
All done
[更新 2] 取消注釋行//queue.maxConcurrentOperationCount = 1
時的輸出
search( :in:Centered:id:):第0部分的本地搜索 2020-03-28 23:49:41 +0000 search( :in: Centered :id:):等待第0部分完成 2020-03 -28 23:49:41 +0000 搜索( :in: central :id:): ***警告:第 0 次超時,作業未完成 2020-03-28 23:49:46 +0000 搜索( :in: central :id :):第一部分的本地搜索 2020-03-28 23:49:46 +0000 search( :in: central :id:):等待第一部分完成 2020-03-28 23:49:46 + 0000 search( :in:central:id:): ***警告:第 1 次超時,作業未完成 2020-03-28 23:49:51 +0000 search( :in: centric :id:):2 號本地搜索部分 2020-03-28 23:49:51 +0000 搜索( :in: Centered :id:):等待第二部分完成 2020-03-28 23:49:51 +0000 搜索( :in:centered: id:): ***警告: 第二次超時, 作業未完成 2020-03-28 23:49:56 +0000 搜索 ( :in: center :id:): 第三部分的本地搜索 2020-03-28 23: 49:56 +0000 搜索( :in: central :id:): 等待第三部分完成 2020-03-28 23:49:56 +0000 搜索( : in:central:id:): ***警告:第 3 次超時,作業未完成 2020-03-28 23:50:01 +0000 全部完成 2020-03-28 23:50:01 +0000 0 got Optional(10) items 2020-03-28 23:50:02 +0000 3 got Optional(10) items 2020-03-28 23:50:02 +0000 2 got Optional(10) items 2020-03-28 23:50:02 + 0000 1 得到 Optional(10) items 2020-03-28 23:50:02 +0000
注意:順便說一句,我還在每次打印的末尾添加了\\(Date())
如果您希望這些操作以串行方式運行,則必須指定隊列一次只能運行一個,例如
queue.maxConcurrentOperationCount = 1
而且,正如你發現,你要避免使用waitUntilFinished
的選項addOperations
,為阻止當前線程,直到操作完成。 相反,使用完成處理程序模式。
這是我使用的代碼:
func performMultipleSearches(completion: @escaping () -> Void) {
let searches = ["restaurant", "coffee", "hospital", "natural history museum"]
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
for (i, searchText) in searches.enumerated() {
queue.addOperation {
self.search(searchText, in: self.mapView.region, id: i)
}
}
queue.addOperation {
completion()
}
}
func search(_ query: String, in region: MKCoordinateRegion, id: Int) {
let semaphore = DispatchSemaphore(value: 0)
os_log("%d starting", id)
let request = MKLocalSearch.Request()
request.naturalLanguageQuery = query
request.region = region
if #available(iOS 13, *) {
request.resultTypes = .pointOfInterest
}
let search = MKLocalSearch(request: request)
search.start { response, error in
defer { semaphore.signal() }
guard let mapItems = response?.mapItems else {
os_log(" %d failed", id)
return
}
os_log(" %d succeeded, found %d:", id, mapItems.count)
}
os_log(" %d waiting", id)
guard semaphore.wait(timeout: .now() + 5) == .success else {
os_log(" %d timedout", id)
return
}
os_log(" %d done", id)
}
這產生了:
2020-03-28 16:16:25.219565-0700 MyApp[46601:2107182] 0 starting
2020-03-28 16:16:25.220018-0700 MyApp[46601:2107182] 0 waiting
2020-03-28 16:16:25.438121-0700 MyApp[46601:2107033] 0 succeeded, found 10:
2020-03-28 16:16:25.438269-0700 MyApp[46601:2107182] 0 done
2020-03-28 16:16:25.438436-0700 MyApp[46601:2107182] 1 starting
2020-03-28 16:16:25.438566-0700 MyApp[46601:2107182] 1 waiting
2020-03-28 16:16:25.639198-0700 MyApp[46601:2107033] 1 succeeded, found 10:
2020-03-28 16:16:25.639357-0700 MyApp[46601:2107182] 1 done
2020-03-28 16:16:25.639490-0700 MyApp[46601:2107182] 2 starting
2020-03-28 16:16:25.639598-0700 MyApp[46601:2107182] 2 waiting
2020-03-28 16:16:25.822085-0700 MyApp[46601:2107033] 2 succeeded, found 10:
2020-03-28 16:16:25.822274-0700 MyApp[46601:2107182] 2 done
2020-03-28 16:16:25.822422-0700 MyApp[46601:2107162] 3 starting
2020-03-28 16:16:25.822567-0700 MyApp[46601:2107162] 3 waiting
2020-03-28 16:16:26.015566-0700 MyApp[46601:2107033] 3 succeeded, found 1:
2020-03-28 16:16:26.015696-0700 MyApp[46601:2107162] 3 done
2020-03-28 16:16:26.015840-0700 MyApp[46601:2107162] all done
就其價值而言,我不會使用信號量,而是使用異步Operation
子類。 例如,您可以使用此處定義的AsynchronousOperation
類,然后執行以下操作:
class SearchOperation: AsynchronousOperation {
let identifier: Int
let searchText: String
let region: MKCoordinateRegion
init(identifier: Int, searchText: String, region: MKCoordinateRegion) {
self.identifier = identifier
self.searchText = searchText
self.region = region
super.init()
}
override func main() {
os_log("%d started", identifier)
let request = MKLocalSearch.Request()
request.naturalLanguageQuery = searchText
request.region = region
if #available(iOS 13, *) {
request.resultTypes = .pointOfInterest
}
let search = MKLocalSearch(request: request)
search.start { response, error in
defer { self.finish() }
guard let mapItems = response?.mapItems else {
os_log(" %d failed", self.identifier)
return
}
os_log(" %d succeeded, found %d:", self.identifier, mapItems.count)
}
}
}
進而
let searches = ["restaurant", "coffee", "hospital", "natural history museum"]
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
for (i, searchText) in searches.enumerated() {
queue.addOperation(SearchOperation(identifier: i, searchText: searchText, region: mapView.region))
}
queue.addOperation {
completion()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.