Получить предлагаемые поисковые запросы
Чтобы получить предложения по поиску, вызовите метод getSearchSuggestions
в ContextualSearchRuntime
. Этот метод принимает один GetSearchSuggestionsOptions , где вы можете указать текст, который будет использоваться для получения поисковых предложений.
Возвращенный объект SearchSuggestions
не содержит доступных свойств. Он содержит всю необходимую информацию для предоставления поисковых предложений, но в остальном он непрозрачен.
Swift использует стиль Swift Concurrency, Objective-C использует функцию обратного вызова.
Быстрый
getSearchSuggestions(withOptions:)
Task {
let suggestions = try await searchRuntime.getSearchSuggestions(
withOptions: GetSearchSuggestionsOptions(withTextContext:['Sample Query', 'Another query string']))
}
Цель-C
getSearchSuggestionsWithOptions
[searchRuntime
getSearchSuggestionsWithOptions:
[[GetSearchSuggestionsOptions alloc] initWithTextContext: @[@'Sample Query', @'Another query string' ]]
completionHandler:^(SearchSuggestions *_Nullable suggestions,
NSError *_Nullable error) {
// error will be not null if there is an error.
// On success, suggestions will be non null.
}];
Получите предлагаемые поисковые запросы на основе местоположения
Запрос getSearchSuggestions
также поддерживает предложения поиска на основе местоположения. Создайте объект GetSearchSuggestionsOptions
с помощью LocationSuggestionsContext .
Выполните следующие шаги, чтобы создать класс LocationSuggestionsContext
:
- (Обязательно) Установите
latitude
,longitude
иradiusMeters
в соответствии с запрошенной областью. - (Необязательно) Установите
startTime
, чтобы оно соответствовало запрошенному времени, в которое должны применяться поисковые предложения. - (Необязательно) Установите список
geoTypes
с запрошенными типами гео. Предоставленные типы используются для настройки ранжирования и фильтрации результатов, возвращаемых службой. Поддерживаемые значения описаны в LocationSuggestionsContext .
Быстрый
getSearchSuggestions(withOptions:)
Task {
let locationContext: LocationSuggestionsContext = {
let context = LocationSuggestionsContext()
context.latitude = 40.748595
context.longitude = -73.992365
context.radiusMeters = 2500
context.startTime = try?
Date.ISO8601FormatStyle.iso8601.parse("2024-03-14T19:20:30.000+02:00")
context.geoTypes = ["restaurant", "cafe"]
return context
}()
let suggestions = try await searchRuntime.getSearchSuggestions(
withOptions: GetSearchSuggestionsOptions(locationContext: [
locationContext
]))
}
Цель-C
getSearchSuggestionsWithOptions
LocationSuggestionsContext *locationContext;
locationContext = [[LocationSuggestionsContext alloc] init];
locationContext.latitude = 40.748595;
locationContext.longitude = -73.992365;
locationContext.radiusMeters = @2500;
[searchRuntime
getSearchSuggestionsWithOptions:
[[GetSearchSuggestionsOptions alloc] initWithLocationContext: locationContext]
completionHandler:^(SearchSuggestions *_Nullable suggestions,
NSError *_Nullable error) {
// error will be not null if there is an error.
// On success, suggestions will be non null.
}];
Отображать
Чтобы отобразить чипы поисковых предложений, используйте следующие методы (стиль различается, если вы используете UIKit или SwiftUI).
Swift UIKit
Отобразите чипы предложений по поиску с помощью SearchSuggestionsViewController .
// Create the SearchSuggestionsViewController with specified display options.
var searchSuggestionsController = SearchSuggestionsViewController(options: viewOptions)
...
// Add the view controller to the existing view hierarchy
searchSuggestionsController.addToViewContoller(self)
view.addSubview(searchSuggestionsController.view)
...
// Assign a specific set of search suggestions to this view controller.
searchSuggestionsController.searchSuggestions = suggestions
Цель-C
Отобразите чипы предложений по поиску с помощью SearchSuggestionsViewController .
// Create the SearchSuggestionsController with specified display options.
SearchSuggestionsViewController *_searchSuggestionsController =
[[SearchSuggestionsViewController alloc] initWithOptions:_customizationOptions];
...
// Add the view controller to the existing view hierarchy
[_searchSuggestionsController addToViewController:self];
[self.view addSubview:_searchSuggestionsController.view];
...
// Assign a specific set of search suggestions to this view controller.
_searchSuggestionsController.searchSuggestions = suggestions
SwiftUI
Предложения поиска могут отображаться с помощью SearchSuggestionsView.
SearchSuggestionsView(suggestions: suggestions, options: options)