Мои mkmarkerannotationviews не появляются на карте. Что я делаю не так? Сообщения, которые говорят: < /p>
Нет пакетов конфигурации типа, доступных для ключа: [Spr USA Bay Area Area Laure, 3.000000]
Не удалось разрешить Packnam Guides_icons_default@3x.icondatapack, expert_partners_icons@3x.iconconfigpack, default_icons@3x.iconconfigpack, expert_partners_icons@3x.icondatapack, default_icons@3x.icondatapcac Default@3x.iconmappack, default_shields@3x.icondatapack] < /p>
< /blockquote>
Нет конфигурации, не найденный для ключей и значков San Francisco
no type packs of type для ключа: [Spr USA Bay Area Landmarks, 3.00000000 affee of type of type: [Spr USA Bay Area. /> < /blockquote>
Существует больше из приведенных выше сообщений уведомлений, которые отличаются, и я думаю, что именно здесь может быть моя проблема, однако символы SF уже загружены в XCode (я посмотрел это вверх). Я погуглил некоторые из этих сообщений об ошибках и не смог найти полезные решения моей проблемы. Я также погуглил, как добавить соответствующие пакеты в мой проект, и не смог найти ничего, что применимо к достопримечательностям SPR USA Bay Area или значкам Сан -Франциско. < /P>
Я прикрепил свой код ниже.CitiesMapViewController.swift:
import UIKit
import MapKit
import FloatingPanel
import CoreLocation
class CitiesMapViewController: UIViewController, MKMapViewDelegate, CitiesMapViewPanelSearchBarViewControllerDelegate, CLLocationManagerDelegate {
var selectedLocationViewModel: SelectedLocationViewModel!
let manager = CLLocationManager()
var venues: [CompleteInitialVenueInfoWithOpenAtSatSun201AMDateTime_FriSatForUserOpenAfter2AMProperties] = []
let myMapView = MKMapView()
let panel = FloatingPanelController()
private let nightBitesLabel: UILabel = {
let label = UILabel()
label.text = "Night Bites"
label.font = .systemFont(ofSize: 18, weight: .semibold)
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(myMapView)
view.addSubview(nightBitesLabel)
myMapView.delegate = self
let citiesMapViewPanelSearchBarVC = CitiesMapViewPanelSearchBarViewController()
citiesMapViewPanelSearchBarVC.delegate = self
panel.set(contentViewController: citiesMapViewPanelSearchBarVC)
panel.addPanel(toParent: self)
manager.requestAlwaysAuthorization()
manager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
}
else {
print("Error after pressing UserLocationButton (and possibly related to the GPS, per Question Poster's code and thought), after the line of code: 'if CLLocationManager.locationServicesEnabled() {'" )
}
self.makingVenuesMapVenuesAndAddingToMap(venues: self.venues)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
myMapView.frame = view.bounds
nightBitesLabel.sizeToFit()
nightBitesLabel.frame = CGRect(x: 18, y: 38, width: nightBitesLabel.frame.size.width, height: nightBitesLabel.frame.size.height)
}
override func viewDidAppear(_ animated: Bool) {
manager.requestAlwaysAuthorization()
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
self.myMapView.showsUserLocation = true
self.myMapView.userTrackingMode = .follow
}
func showSelectedCityAreaRestaurantsAsPins(_ vc: CitiesMapViewPanelSearchBarViewController, didSelectLocationWith coordinates: CLLocationCoordinate2D?, latitudeForRetrievingData: Double?, longitudeForRetrievingData: Double?, venues: [CompleteInitialVenueInfoWithOpenAtSatSun201AMDateTime_FriSatForUserOpenAfter2AMProperties] = []) {
guard let coordinates = coordinates else {
return
}
panel.move(to: .tip, animated: true)
myMapView.removeAnnotations(myMapView.annotations)
//Zooming in the map to the selected City's pin.
myMapView.setRegion(MKCoordinateRegion(center: coordinates, span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5)), animated: true)
Task {
guard let venues = try? await getInitialRestaurantVenueInfoWithIfOpenAtSatOrSun201AMDateTimes_FriOrSatAfter2AMForUserPropertiesForMapView(latitude: latitudeForRetrievingData!,
longitude: longitudeForRetrievingData!,
category: "restaurants",
sortBy: "rating",
openAtForSaturday201AMDateTimeAfterFriday2AMForUser: retrieveNextSaturday201AMDateTimeOriginallyInSelectedLocationTimeZoneTimeInUnixTimeRelativeToTodayForSelectedLocation(),
openAtForSunday201AMDateTimeAfterSaturday2AMForUser: retrieveNextSunday201AMDateTimeOriginallyInSelectedLocationTimeZoneTimeInUnixTimeRelativeToTodayForSelectedLocation()) else {return}
self.venues = venues
}
//For Making each venue in venues MKAnnotations, and NSObjects.
//Creating Empty mapVenuesList called mapVenues.
var mapVenues: [MapVenue] = []
//For loop for Making each venue in venues MKAnnotations, and NSObjects. Bascially which can be used as pins, and which can be added to map when created.
for venue in venues {
var mapVenue = MapVenue(name: venue.name, id: venue.id, latitude: venue.coordinates.latitude, longitude: venue.coordinates.longitude, coordinate: CLLocationCoordinate2D(latitude: venue.coordinates.latitude, longitude: venue.coordinates.longitude), image_url: venue.image_url, rating: venue.rating, is_closed: venue.is_closed, distance: venue.distance)
//Appending a MapVenue to mapVenues.
mapVenues.append(mapVenue)
}
//For adding each mapVenue (is an NSObject, and MKAnnotation, so can be used as a "pin" when adding them to map) to map.
for element in mapVenues {
myMapView.addAnnotation(element)
}
}
func showUserLocationSymbolAndUserLocationAreaRestaurantsAsPins(_ vc: CitiesMapViewPanelSearchBarViewController, didSelectLocationWith coordinates: CLLocationCoordinate2D?, latitudeForRetrievingData: Double?, longitudeForRetrievingData: Double?, venues: [CompleteInitialVenueInfoWithOpenAtSatSun201AMDateTime_FriSatForUserOpenAfter2AMProperties] = []) {
guard let coordinates = coordinates else {
return
}
panel.move(to: .tip, animated: true)
myMapView.removeAnnotations(myMapView.annotations)
//Zooming in the map to the selected City's pin.
myMapView.setRegion(MKCoordinateRegion(center: coordinates, span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5)), animated: true)
Task {
guard let venues = try? await getInitialRestaurantVenueInfoWithIfOpenAtSatOrSun201AMDateTimes_FriOrSatAfter2AMForUserPropertiesForMapView(latitude: latitudeForRetrievingData!,
longitude: longitudeForRetrievingData!,
category: "restaurants",
sortBy: "rating",
openAtForSaturday201AMDateTimeAfterFriday2AMForUser: retrieveNextSaturday201AMDateTimeOriginallyInSelectedLocationTimeZoneTimeInUnixTimeRelativeToTodayForSelectedLocation(),
openAtForSunday201AMDateTimeAfterSaturday2AMForUser: retrieveNextSunday201AMDateTimeOriginallyInSelectedLocationTimeZoneTimeInUnixTimeRelativeToTodayForSelectedLocation()) else {return}
self.venues = venues
}
self.makingVenuesMapVenuesAndAddingToMap(venues: self.venues)
}
func makingVenuesMapVenuesAndAddingToMap(venues: [CompleteInitialVenueInfoWithOpenAtSatSun201AMDateTime_FriSatForUserOpenAfter2AMProperties]) {
//For Making each venue in venues MKAnnotations, and NSObjects.
//Creating Empty mapVenuesList called mapVenues.
var mapVenues: [MapVenue] = []
//For loop for Making each venue in venues MKAnnotations, and NSObjects. Bascially which can be used as pins, and which can be added to map when created.
for venue in venues {
var mapVenue = MapVenue(name: venue.name, id: venue.id, latitude: venue.coordinates.latitude, longitude: venue.coordinates.longitude, coordinate: CLLocationCoordinate2D(latitude: venue.coordinates.latitude, longitude: venue.coordinates.longitude), image_url: venue.image_url, rating: venue.rating, is_closed: venue.is_closed, distance: venue.distance)
//Appending aMapVenue to mapVenues.
mapVenues.append(mapVenue)
}
//For adding each mapVenue (is an NSObject, and MKAnnotation, so can be used as a "pin" when adding them to map) to map.
for element in mapVenues {
myMapView.addAnnotation(element)
}
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
let restaurantPinAnnotationView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: "MyMarker")
restaurantPinAnnotationView.markerTintColor = UIColor.orange
restaurantPinAnnotationView.glyphImage = UIImage(named: "fork_and_knife")
restaurantPinAnnotationView.glyphTintColor = UIColor.white
return restaurantPinAnnotationView
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
guard let mapVenue = view.annotation as? MapVenue else { return }
presentSDVCitiesSelectedRestaurantFromMapModal(mapVenue: mapVenue)
}
private func presentSDVCitiesSelectedRestaurantFromMapModal(mapVenue: MapVenue) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let sdvCitiesSelectedRestaurantFromMapVC = storyboard.instantiateViewController(identifier: "SDVCitiesSelectedRestaurantFromMapViewController") as! SDVCitiesSelectedRestaurantFromMapViewController
let nav = UINavigationController(rootViewController: sdvCitiesSelectedRestaurantFromMapVC)
nav.setNavigationBarHidden(true, animated: false)
nav.modalPresentationStyle = .pageSheet
if let sheet = nav.sheetPresentationController {
sheet.detents = [.medium(), .large()]
sheet.prefersGrabberVisible = true
}
sdvCitiesSelectedRestaurantFromMapVC.theMapVenue = mapVenue
present(nav, animated: true, completion: nil)
}
}
class MapVenue: NSObject, MKAnnotation {
var name: String?
var id: String?
var latitude: Double?
var longitude: Double?
var coordinate: CLLocationCoordinate2D
var image_url: String?
var rating: Double?
var is_closed: Bool?
var distance: Double?
var title: String? {
return name
}
init(name: String?,
id: String?,
latitude: Double?,
longitude: Double?,
coordinate: CLLocationCoordinate2D,
image_url: String?,
rating: Double?,
is_closed: Bool?,
distance: Double?) {
self.name = name
self.id = id
self.latitude = latitude
self.longitude = longitude
self.coordinate = coordinate
self.image_url = image_url
self.rating = rating
self.is_closed = is_closed
self.distance = distance
}
}
Примечание: в приведенном выше файле CitiesmapviewController.swift , в строке:
if CLLocationManager.locationServicesEnabled() {
< /code>
Есть предупреждающий знак: < /p>
Этот метод может привести к невосприимчивости пользовательского интерфейса, если он вызван в основном потоке. Вместо этого рассмотрите возможность ждать -location managerdidchangeauthorization: обратный вызов и проверка AuthorizationStatus сначала.
GetInitiallyDisplayedRestaurantVenueData.swift:
import Foundation
import CoreLocation
extension CitiesMapViewController {
func getInitialRestaurantVenueInfoWithIfOpenAtSatOrSun201AMDateTimes_FriOrSatAfter2AMForUserPropertiesForMapView(latitude: Double,
longitude: Double,
category: String,
sortBy: String,
openAtForSaturday201AMDateTimeAfterFriday2AMForUser: Int?,
openAtForSunday201AMDateTimeAfterSaturday2AMForUser: Int?) async throws -> [CompleteInitialVenueInfoWithOpenAtSatSun201AMDateTime_FriSatForUserOpenAfter2AMProperties] {
//Initiializing API Class.
let yelpApi = YelpApi(apiKey: "tWzol4FnOlw5vsyfxPf0nfoy0pSb3gK0qe-JMQtvhieXc3DbEu-URhilG54F_ZIJtCTcRMU3-CMUm7sF32ulQIekLBUN1zcqKazobta38RK0KTL7XXP15CqZkKYKYnYx")
do {
async let responseSatDateTime = try await yelpApi.searchBusiness(latitude: latitude, longitude: longitude, category: category, sortBy: sortBy, openAt: openAtForSaturday201AMDateTimeAfterFriday2AMForUser)
async let responseSunDateTime = try await yelpApi.searchBusiness(latitude: latitude, longitude: longitude, category: category, sortBy: sortBy, openAt: openAtForSunday201AMDateTimeAfterSaturday2AMForUser)
let responses = try await [responseSatDateTime, responseSunDateTime]
let completeVenuesListWithIfOpenOnSatOrSun_FriOrSatForUserAt201AMDateTimesProperties = createCompleteVenuesListWithIfOpenOnSatOrSun_FriOrSatForUserAt201AMDateTimesProperties(venuesThatAreOpenAtSat201AMDateTime_FriNightAfter2AMForUser: responses[0], venuesThatAreOpenAtSun201AMDateTime_SatNigthAfter2AMForUser: responses[1])
return completeVenuesListWithIfOpenOnSatOrSun_FriOrSatForUserAt201AMDateTimesProperties
} catch {
print("Error info for catch block in Task block in getInitialRestaurantVenueInfoWithIfOpenAtSatOrSun201AMDateTimes_FriOrSatAFter2AMForUserProperties for making API request: \(error)")
throw error
}
}
}
< /code>
Class YelpApi.swift:
import Foundation
import CoreLocation
class YelpApi {
enum SortOption: String {
case bestMatch="best_match"
case rating="rating"
case reviewCount="review_count"
case distance="distance"
}
private var apiKey: String
init(apiKey: String) {
self.apiKey = apiKey
}
func searchBusiness(latitude: Double,
longitude: Double,
category: String,
sortBy: String,
openAt: Int?) async throws -> [InitiallyDisplayedRestaurantVenueInfo] {
var queryItems = [URLQueryItem]()
queryItems.append(URLQueryItem(name:"latitude",value:"\(latitude)"))
queryItems.append(URLQueryItem(name:"longitude",value:"\(longitude)"))
queryItems.append(URLQueryItem(name:"categories", value:category))
queryItems.append(URLQueryItem(name:"sort_by",value:sortBy))
if let openAt = openAt {
queryItems.append(URLQueryItem(name:"open_at", value:"\(openAt)"))
}
var results = [InitiallyDisplayedRestaurantVenueInfo]()
var expectedCount = 0
let countLimit = 50
var offset = 0
queryItems.append(URLQueryItem(name:"limit", value:"\(countLimit)"))
repeat {
var offsetQueryItems = queryItems
offsetQueryItems.append(URLQueryItem(name:"offset",value: "\(offset)"))
var urlComponents = URLComponents(string: "https://api.yelp.com/v3/businesses/search")
urlComponents?.queryItems = offsetQueryItems
guard let url = urlComponents?.url else {
throw URLError(.badURL)
}
var request = URLRequest(url: url)
request.setValue("Bearer \(self.apiKey)", forHTTPHeaderField: "Authorization")
let (data, _) = try await URLSession.shared.data(for: request)
let businessResults = try JSONDecoder().decode(BusinessSearchResult.self, from: data)
expectedCount = min(businessResults.total,1000)
results.append(contentsOf: businessResults.businesses)
offset += businessResults.businesses.count
} while (countLimit + offset < 241)
return results
}
}
< /code>
InitiallyDisplayedRestaurantVenueInfo-Struct.swift:
import Foundation
// MARK: - BusinessSearchResult
struct BusinessSearchResult: Codable {
let total: Int
let businesses: [InitiallyDisplayedRestaurantVenueInfo]
let region: Region
}
// MARK: - Business
struct InitiallyDisplayedRestaurantVenueInfo: Codable {
let rating: Double
let price, phone, alias: String?
let id: String
let is_closed: Bool?
let categories: [Category]
let review_count: Int?
let name: String?
let url: String?
let coordinates: Center
let image_url: String?
let location: LocationOfRestaurant?
let distance: Double
let transactions: [String]
}
// MARK: - Category
struct Category: Codable {
let alias, title: String
}
// MARK: - Center
struct Center: Codable {
let latitude, longitude: Double
}
// MARK: - Location
struct LocationOfRestaurant: Codable {
let city, country, address2, address3: String?
let state, address1, zipCode: String?
}
// MARK: - Region
struct Region: Codable {
let center: Center
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... ing-on-map
Mkmarkerannotationviews не появляется на карте ⇐ IOS
Программируем под IOS
-
Anonymous
1747439089
Anonymous
Мои mkmarkerannotationviews не появляются на карте. Что я делаю не так? Сообщения, которые говорят: < /p>
Нет пакетов конфигурации типа, доступных для ключа: [Spr USA Bay Area Area Laure, 3.000000]
Не удалось разрешить Packnam Guides_icons_default@3x.icondatapack, expert_partners_icons@3x.iconconfigpack, default_icons@3x.iconconfigpack, expert_partners_icons@3x.icondatapack, default_icons@3x.icondatapcac Default@3x.iconmappack, default_shields@3x.icondatapack] < /p>
< /blockquote>
Нет конфигурации, не найденный для ключей и значков San Francisco
no type packs of type для ключа: [Spr USA Bay Area Landmarks, 3.00000000 affee of type of type: [Spr USA Bay Area. /> < /blockquote>
Существует больше из приведенных выше сообщений уведомлений, которые отличаются, и я думаю, что именно здесь может быть моя проблема, однако символы SF уже загружены в XCode (я посмотрел это вверх). Я погуглил некоторые из этих сообщений об ошибках и не смог найти полезные решения моей проблемы. Я также погуглил, как добавить соответствующие пакеты в мой проект, и не смог найти ничего, что применимо к достопримечательностям SPR USA Bay Area или значкам Сан -Франциско. < /P>
Я прикрепил свой код ниже.CitiesMapViewController.swift:
import UIKit
import MapKit
import FloatingPanel
import CoreLocation
class CitiesMapViewController: UIViewController, MKMapViewDelegate, CitiesMapViewPanelSearchBarViewControllerDelegate, CLLocationManagerDelegate {
var selectedLocationViewModel: SelectedLocationViewModel!
let manager = CLLocationManager()
var venues: [CompleteInitialVenueInfoWithOpenAtSatSun201AMDateTime_FriSatForUserOpenAfter2AMProperties] = []
let myMapView = MKMapView()
let panel = FloatingPanelController()
private let nightBitesLabel: UILabel = {
let label = UILabel()
label.text = "Night Bites"
label.font = .systemFont(ofSize: 18, weight: .semibold)
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(myMapView)
view.addSubview(nightBitesLabel)
myMapView.delegate = self
let citiesMapViewPanelSearchBarVC = CitiesMapViewPanelSearchBarViewController()
citiesMapViewPanelSearchBarVC.delegate = self
panel.set(contentViewController: citiesMapViewPanelSearchBarVC)
panel.addPanel(toParent: self)
manager.requestAlwaysAuthorization()
manager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
}
else {
print("Error after pressing UserLocationButton (and possibly related to the GPS, per Question Poster's code and thought), after the line of code: 'if CLLocationManager.locationServicesEnabled() {'" )
}
self.makingVenuesMapVenuesAndAddingToMap(venues: self.venues)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
myMapView.frame = view.bounds
nightBitesLabel.sizeToFit()
nightBitesLabel.frame = CGRect(x: 18, y: 38, width: nightBitesLabel.frame.size.width, height: nightBitesLabel.frame.size.height)
}
override func viewDidAppear(_ animated: Bool) {
manager.requestAlwaysAuthorization()
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
self.myMapView.showsUserLocation = true
self.myMapView.userTrackingMode = .follow
}
func showSelectedCityAreaRestaurantsAsPins(_ vc: CitiesMapViewPanelSearchBarViewController, didSelectLocationWith coordinates: CLLocationCoordinate2D?, latitudeForRetrievingData: Double?, longitudeForRetrievingData: Double?, venues: [CompleteInitialVenueInfoWithOpenAtSatSun201AMDateTime_FriSatForUserOpenAfter2AMProperties] = []) {
guard let coordinates = coordinates else {
return
}
panel.move(to: .tip, animated: true)
myMapView.removeAnnotations(myMapView.annotations)
//Zooming in the map to the selected City's pin.
myMapView.setRegion(MKCoordinateRegion(center: coordinates, span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5)), animated: true)
Task {
guard let venues = try? await getInitialRestaurantVenueInfoWithIfOpenAtSatOrSun201AMDateTimes_FriOrSatAfter2AMForUserPropertiesForMapView(latitude: latitudeForRetrievingData!,
longitude: longitudeForRetrievingData!,
category: "restaurants",
sortBy: "rating",
openAtForSaturday201AMDateTimeAfterFriday2AMForUser: retrieveNextSaturday201AMDateTimeOriginallyInSelectedLocationTimeZoneTimeInUnixTimeRelativeToTodayForSelectedLocation(),
openAtForSunday201AMDateTimeAfterSaturday2AMForUser: retrieveNextSunday201AMDateTimeOriginallyInSelectedLocationTimeZoneTimeInUnixTimeRelativeToTodayForSelectedLocation()) else {return}
self.venues = venues
}
//For Making each venue in venues MKAnnotations, and NSObjects.
//Creating Empty mapVenuesList called mapVenues.
var mapVenues: [MapVenue] = []
//For loop for Making each venue in venues MKAnnotations, and NSObjects. Bascially which can be used as pins, and which can be added to map when created.
for venue in venues {
var mapVenue = MapVenue(name: venue.name, id: venue.id, latitude: venue.coordinates.latitude, longitude: venue.coordinates.longitude, coordinate: CLLocationCoordinate2D(latitude: venue.coordinates.latitude, longitude: venue.coordinates.longitude), image_url: venue.image_url, rating: venue.rating, is_closed: venue.is_closed, distance: venue.distance)
//Appending a MapVenue to mapVenues.
mapVenues.append(mapVenue)
}
//For adding each mapVenue (is an NSObject, and MKAnnotation, so can be used as a "pin" when adding them to map) to map.
for element in mapVenues {
myMapView.addAnnotation(element)
}
}
func showUserLocationSymbolAndUserLocationAreaRestaurantsAsPins(_ vc: CitiesMapViewPanelSearchBarViewController, didSelectLocationWith coordinates: CLLocationCoordinate2D?, latitudeForRetrievingData: Double?, longitudeForRetrievingData: Double?, venues: [CompleteInitialVenueInfoWithOpenAtSatSun201AMDateTime_FriSatForUserOpenAfter2AMProperties] = []) {
guard let coordinates = coordinates else {
return
}
panel.move(to: .tip, animated: true)
myMapView.removeAnnotations(myMapView.annotations)
//Zooming in the map to the selected City's pin.
myMapView.setRegion(MKCoordinateRegion(center: coordinates, span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5)), animated: true)
Task {
guard let venues = try? await getInitialRestaurantVenueInfoWithIfOpenAtSatOrSun201AMDateTimes_FriOrSatAfter2AMForUserPropertiesForMapView(latitude: latitudeForRetrievingData!,
longitude: longitudeForRetrievingData!,
category: "restaurants",
sortBy: "rating",
openAtForSaturday201AMDateTimeAfterFriday2AMForUser: retrieveNextSaturday201AMDateTimeOriginallyInSelectedLocationTimeZoneTimeInUnixTimeRelativeToTodayForSelectedLocation(),
openAtForSunday201AMDateTimeAfterSaturday2AMForUser: retrieveNextSunday201AMDateTimeOriginallyInSelectedLocationTimeZoneTimeInUnixTimeRelativeToTodayForSelectedLocation()) else {return}
self.venues = venues
}
self.makingVenuesMapVenuesAndAddingToMap(venues: self.venues)
}
func makingVenuesMapVenuesAndAddingToMap(venues: [CompleteInitialVenueInfoWithOpenAtSatSun201AMDateTime_FriSatForUserOpenAfter2AMProperties]) {
//For Making each venue in venues MKAnnotations, and NSObjects.
//Creating Empty mapVenuesList called mapVenues.
var mapVenues: [MapVenue] = []
//For loop for Making each venue in venues MKAnnotations, and NSObjects. Bascially which can be used as pins, and which can be added to map when created.
for venue in venues {
var mapVenue = MapVenue(name: venue.name, id: venue.id, latitude: venue.coordinates.latitude, longitude: venue.coordinates.longitude, coordinate: CLLocationCoordinate2D(latitude: venue.coordinates.latitude, longitude: venue.coordinates.longitude), image_url: venue.image_url, rating: venue.rating, is_closed: venue.is_closed, distance: venue.distance)
//Appending aMapVenue to mapVenues.
mapVenues.append(mapVenue)
}
//For adding each mapVenue (is an NSObject, and MKAnnotation, so can be used as a "pin" when adding them to map) to map.
for element in mapVenues {
myMapView.addAnnotation(element)
}
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
let restaurantPinAnnotationView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: "MyMarker")
restaurantPinAnnotationView.markerTintColor = UIColor.orange
restaurantPinAnnotationView.glyphImage = UIImage(named: "fork_and_knife")
restaurantPinAnnotationView.glyphTintColor = UIColor.white
return restaurantPinAnnotationView
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
guard let mapVenue = view.annotation as? MapVenue else { return }
presentSDVCitiesSelectedRestaurantFromMapModal(mapVenue: mapVenue)
}
private func presentSDVCitiesSelectedRestaurantFromMapModal(mapVenue: MapVenue) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let sdvCitiesSelectedRestaurantFromMapVC = storyboard.instantiateViewController(identifier: "SDVCitiesSelectedRestaurantFromMapViewController") as! SDVCitiesSelectedRestaurantFromMapViewController
let nav = UINavigationController(rootViewController: sdvCitiesSelectedRestaurantFromMapVC)
nav.setNavigationBarHidden(true, animated: false)
nav.modalPresentationStyle = .pageSheet
if let sheet = nav.sheetPresentationController {
sheet.detents = [.medium(), .large()]
sheet.prefersGrabberVisible = true
}
sdvCitiesSelectedRestaurantFromMapVC.theMapVenue = mapVenue
present(nav, animated: true, completion: nil)
}
}
class MapVenue: NSObject, MKAnnotation {
var name: String?
var id: String?
var latitude: Double?
var longitude: Double?
var coordinate: CLLocationCoordinate2D
var image_url: String?
var rating: Double?
var is_closed: Bool?
var distance: Double?
var title: String? {
return name
}
init(name: String?,
id: String?,
latitude: Double?,
longitude: Double?,
coordinate: CLLocationCoordinate2D,
image_url: String?,
rating: Double?,
is_closed: Bool?,
distance: Double?) {
self.name = name
self.id = id
self.latitude = latitude
self.longitude = longitude
self.coordinate = coordinate
self.image_url = image_url
self.rating = rating
self.is_closed = is_closed
self.distance = distance
}
}
Примечание: в приведенном выше файле CitiesmapviewController.swift , в строке:
if CLLocationManager.locationServicesEnabled() {
< /code>
Есть предупреждающий знак: < /p>
Этот метод может привести к невосприимчивости пользовательского интерфейса, если он вызван в основном потоке. Вместо этого рассмотрите возможность ждать -location managerdidchangeauthorization: обратный вызов и проверка AuthorizationStatus сначала.
GetInitiallyDisplayedRestaurantVenueData.swift:
import Foundation
import CoreLocation
extension CitiesMapViewController {
func getInitialRestaurantVenueInfoWithIfOpenAtSatOrSun201AMDateTimes_FriOrSatAfter2AMForUserPropertiesForMapView(latitude: Double,
longitude: Double,
category: String,
sortBy: String,
openAtForSaturday201AMDateTimeAfterFriday2AMForUser: Int?,
openAtForSunday201AMDateTimeAfterSaturday2AMForUser: Int?) async throws -> [CompleteInitialVenueInfoWithOpenAtSatSun201AMDateTime_FriSatForUserOpenAfter2AMProperties] {
//Initiializing API Class.
let yelpApi = YelpApi(apiKey: "tWzol4FnOlw5vsyfxPf0nfoy0pSb3gK0qe-JMQtvhieXc3DbEu-URhilG54F_ZIJtCTcRMU3-CMUm7sF32ulQIekLBUN1zcqKazobta38RK0KTL7XXP15CqZkKYKYnYx")
do {
async let responseSatDateTime = try await yelpApi.searchBusiness(latitude: latitude, longitude: longitude, category: category, sortBy: sortBy, openAt: openAtForSaturday201AMDateTimeAfterFriday2AMForUser)
async let responseSunDateTime = try await yelpApi.searchBusiness(latitude: latitude, longitude: longitude, category: category, sortBy: sortBy, openAt: openAtForSunday201AMDateTimeAfterSaturday2AMForUser)
let responses = try await [responseSatDateTime, responseSunDateTime]
let completeVenuesListWithIfOpenOnSatOrSun_FriOrSatForUserAt201AMDateTimesProperties = createCompleteVenuesListWithIfOpenOnSatOrSun_FriOrSatForUserAt201AMDateTimesProperties(venuesThatAreOpenAtSat201AMDateTime_FriNightAfter2AMForUser: responses[0], venuesThatAreOpenAtSun201AMDateTime_SatNigthAfter2AMForUser: responses[1])
return completeVenuesListWithIfOpenOnSatOrSun_FriOrSatForUserAt201AMDateTimesProperties
} catch {
print("Error info for catch block in Task block in getInitialRestaurantVenueInfoWithIfOpenAtSatOrSun201AMDateTimes_FriOrSatAFter2AMForUserProperties for making API request: \(error)")
throw error
}
}
}
< /code>
Class YelpApi.swift:
import Foundation
import CoreLocation
class YelpApi {
enum SortOption: String {
case bestMatch="best_match"
case rating="rating"
case reviewCount="review_count"
case distance="distance"
}
private var apiKey: String
init(apiKey: String) {
self.apiKey = apiKey
}
func searchBusiness(latitude: Double,
longitude: Double,
category: String,
sortBy: String,
openAt: Int?) async throws -> [InitiallyDisplayedRestaurantVenueInfo] {
var queryItems = [URLQueryItem]()
queryItems.append(URLQueryItem(name:"latitude",value:"\(latitude)"))
queryItems.append(URLQueryItem(name:"longitude",value:"\(longitude)"))
queryItems.append(URLQueryItem(name:"categories", value:category))
queryItems.append(URLQueryItem(name:"sort_by",value:sortBy))
if let openAt = openAt {
queryItems.append(URLQueryItem(name:"open_at", value:"\(openAt)"))
}
var results = [InitiallyDisplayedRestaurantVenueInfo]()
var expectedCount = 0
let countLimit = 50
var offset = 0
queryItems.append(URLQueryItem(name:"limit", value:"\(countLimit)"))
repeat {
var offsetQueryItems = queryItems
offsetQueryItems.append(URLQueryItem(name:"offset",value: "\(offset)"))
var urlComponents = URLComponents(string: "https://api.yelp.com/v3/businesses/search")
urlComponents?.queryItems = offsetQueryItems
guard let url = urlComponents?.url else {
throw URLError(.badURL)
}
var request = URLRequest(url: url)
request.setValue("Bearer \(self.apiKey)", forHTTPHeaderField: "Authorization")
let (data, _) = try await URLSession.shared.data(for: request)
let businessResults = try JSONDecoder().decode(BusinessSearchResult.self, from: data)
expectedCount = min(businessResults.total,1000)
results.append(contentsOf: businessResults.businesses)
offset += businessResults.businesses.count
} while (countLimit + offset < 241)
return results
}
}
< /code>
InitiallyDisplayedRestaurantVenueInfo-Struct.swift:
import Foundation
// MARK: - BusinessSearchResult
struct BusinessSearchResult: Codable {
let total: Int
let businesses: [InitiallyDisplayedRestaurantVenueInfo]
let region: Region
}
// MARK: - Business
struct InitiallyDisplayedRestaurantVenueInfo: Codable {
let rating: Double
let price, phone, alias: String?
let id: String
let is_closed: Bool?
let categories: [Category]
let review_count: Int?
let name: String?
let url: String?
let coordinates: Center
let image_url: String?
let location: LocationOfRestaurant?
let distance: Double
let transactions: [String]
}
// MARK: - Category
struct Category: Codable {
let alias, title: String
}
// MARK: - Center
struct Center: Codable {
let latitude, longitude: Double
}
// MARK: - Location
struct LocationOfRestaurant: Codable {
let city, country, address2, address3: String?
let state, address1, zipCode: String?
}
// MARK: - Region
struct Region: Codable {
let center: Center
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79626058/mkmarkerannotationviews-not-appearing-on-map[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия