这个本质就是写个培训项目,像往常一样和老师视频,一切OK,我没有。问题在于,在 MapView 上,当您拖动图钉和地址时,由于某种原因,它在括号中,尽管我没有在任何地方添加额外的括号。这是我们拥有的:
这是代码:
import UIKit
import MapKit
import CoreLocation
protocol MapViewControllerDelegate {
func getAddress(_ address: String?)
}
class MapViewController: UIViewController {
var mapViewControllerDelegate: MapViewControllerDelegate?
var place = Place()
var annatationIndentifier = "annatationIndentifier"
var locationManager = CLLocationManager()
var distanceOfMethre: Double = 10_000.00
var incomeSegueIndetifire = ""
var placeCoordinate: CLLocationCoordinate2D?
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var mapPinImage: UIImageView!
@IBOutlet weak var doneButton: UIButton!
@IBOutlet weak var addressLable: UILabel!
@IBOutlet weak var goButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
addressLable.text = ""
mapView.delegate = self
setupMapView()
checkLocationServices()
}
@IBAction func doneButtonPressed() {
mapViewControllerDelegate?.getAddress(addressLable.text)
dismiss(animated: true, completion: nil)
}
@IBAction func centerViweInUserLocdtion() {
showUserLocation()
}
@IBAction func goButtonPressed() {
getDirections()
}
@IBAction func closeVC() {
dismiss(animated: true, completion: nil)
}
private func setupMapView(){
goButton.isHidden = true
if incomeSegueIndetifire == "showPlace"{
setupPlaceMark()
mapPinImage.isHidden = true
addressLable.isHidden = true
doneButton.isHidden = true
goButton.isHidden = false
}
}
private func setupPlaceMark(){
guard let location = place.location else {return}
let geocode = CLGeocoder()
geocode.geocodeAddressString(location) { (placemarks, error) in
if let error = error {
print(error)
return
}
guard let placemarks = placemarks else { return }
let placemark = placemarks.first
let annatation = MKPointAnnotation()
annatation.title = self.place.name
annatation.subtitle = self.place.type
guard let placemarkLocation = placemark?.location else {return}
annatation.coordinate = placemarkLocation.coordinate
self.placeCoordinate = placemarkLocation.coordinate
self.mapView.showAnnotations([annatation], animated: true)
self.mapView.selectAnnotation(annatation, animated: true)
}
}
private func checkLocationServices(){
if CLLocationManager.locationServicesEnabled(){
setupLocationManager()
checkLocationAutorization()
} else{
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.showAlert(title: "Your Location is not Available",
message: "To give permission Go to: Setting -> MyPlaces -> Location")
}
}
}
private func setupLocationManager(){
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
private func checkLocationAutorization(){
switch locationManager.authorizationStatus {
case .authorizedWhenInUse:
if incomeSegueIndetifire == "getAddress" {showUserLocation()}
mapView.showsUserLocation = true
break
case .denied:
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.showAlert(title: "Your Location is not Available",
message: "To give permission Go to: Setting -> MyPlaces -> Location")
}
break
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
break
case .restricted:
break
case .authorizedAlways:
break
@unknown default:
print("new case is avalible")
}
}
private func showUserLocation(){
if let location = locationManager.location?.coordinate{
let region = MKCoordinateRegion(center: location,
latitudinalMeters: distanceOfMethre,
longitudinalMeters: distanceOfMethre)
mapView.setRegion(region, animated: true)
}
}
private func getDirections(){
guard let location = locationManager.location?.coordinate else {showAlert(title: "Error",
message: "Current location is not found")
return}
guard let request = createDirectionReqest(for: location) else { showAlert(title: "Error",
message: "Distenation is not fount")
return}
let direction = MKDirections(request: request)
direction.calculate { (response, error) in
if let error = error{
print(error)
return
}
guard let response = response else { self.showAlert(title: "Error",
message: "Diretion is not avalible")
return
}
for route in response.routes{
self.mapView.addOverlay(route.polyline)
self.mapView.setVisibleMapRect(route.polyline.boundingMapRect , animated: true )
let distance = String(format: "%.1f", route.distance / 1000)
let timeInterval = route.expectedTravelTime
print("Расстояни в пути \(distance) км")
print("Время в пути \(timeInterval) сек ")
}
}
}
private func createDirectionReqest(for coordinate: CLLocationCoordinate2D) -> MKDirections.Request?{
guard let distanationCoordinate = placeCoordinate else { return nil }
let startingLocatoin = MKPlacemark(coordinate: coordinate)
let destinantion = MKPlacemark(coordinate: distanationCoordinate)
let request = MKDirections.Request()
request.source = MKMapItem(placemark: startingLocatoin)
request.destination = MKMapItem(placemark: destinantion)
request.transportType = .walking
request.requestsAlternateRoutes = true
return request
}
private func getCenterLocation(mapView:MKMapView) -> CLLocation{
let latitude = mapView.centerCoordinate.latitude
let longitude = mapView.centerCoordinate.longitude
return CLLocation(latitude: latitude, longitude: longitude)
}
private func showAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default)
alert.addAction(okAction)
present(alert, animated: true)
}
}
extension MapViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard !(annotation is MKUserLocation) else { return nil }
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annatationIndentifier) as? MKPinAnnotationView
if annotationView == nil{
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: annatationIndentifier)
annotationView?.canShowCallout = true
}
if let imageData = place.imageData{
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
imageView.layer.cornerRadius = 10
imageView.clipsToBounds = true
imageView.image = UIImage(data: imageData)
annotationView?.rightCalloutAccessoryView = imageView
}
return annotationView
}
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
let center = getCenterLocation(mapView: mapView)
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(center) { (placemarks, error) in
if let error = error {
print(error)
return
}
guard let placemarks = placemarks else {return }
let placemark = placemarks.first
let streetName = placemark?.thoroughfare
let buildNumber = placemark?.subThoroughfare
DispatchQueue.main.async {
if streetName != nil && buildNumber != nil {
self.addressLable.text = "(\(streetName!), \(buildNumber!))"
} else if streetName != nil {
self.addressLable.text = "(\(streetName!))"
} else {
self.addressLable.text = ""
}
}
}
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let render = MKPolylineRenderer(overlay: overlay as! MKPolyline)
render.strokeColor = .blue
return render
}
}
extension MapViewController: CLLocationManagerDelegate {
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
checkLocationAutorization()
}
}


删除多余的括号
如果不需要它们:
您还可以摆脱强制展开: