#swift #xcode #mapkit
#swift #xcode #mapkit
Вопрос:
Я ищу место «еда» в моем районе, а возвращаемое значение — это куча ресторанов с их названием. Как бы я случайно выбрал только один из них и вернул название в моем textLabel
? Прямо сейчас он возвращает все названия ресторанов в my textLabel
.
request.region = map.region
request.naturalLanguageQuery = "food"
let search = MKLocalSearch(request: request)
search.start(completionHandler: {(response, error) in
if error != nil {
print("Error occured in search: (error!.localizedDescription)")
} else if response!.mapItems.count == 0 {
print("No matches found")
} else {
print("Matches found")
for item in response!.mapItems {
print("Name = (String(describing: item.name))")
print("Phone = (String(describing: item.phoneNumber))")
let resturantName = SKLabelNode()
resturantName.position = CGPoint(x: self.size.width / 2, y: self.size.height / 3.5)
resturantName.fontSize = 30
resturantName.fontName = "PingFangHK-Semibold"
resturantName.text = item.name
resturantName.fontColor = UIColor.white
resturantName.zPosition = 50
self.addChild(resturantName)
}
}
})
Комментарии:
1. Вы имеете в виду
response!.mapItems.randomElement()
?2. Я пробовал это, но он все еще показывает все строки.
3. Ну
textLabel
, в коде, который вы показали, его нет, поэтому трудно помочь. Ваш код циклически проходит через все элементы карты. Я не знаю, что еще вы «пробовали».4. resturantName — это
label
5.
resturantName.text = item.name
Ответ №1:
Этот фрагмент кода должен работать:
search.start(completionHandler: {(response, error) in
if error != nil {
print("Error occured in search: (error!.localizedDescription)")
} else if response!.mapItems.count == 0 {
print("No matches found")
} else {
print("Matches found")
guard validResponse = response else {return}
//Instead of looping through all of the items, pick one.
let item = validResponse.mapItems.randomElement()
print("Name = (String(describing: item.name))")
print("Phone = (String(describing: item.phoneNumber))")
}
}