Я новичок в Xcode и никогда не создавал приложение для iphone с помощью swift, поэтому у меня все еще много проблем с этим.
В моем приложении я хочу открыть картустраницу и хотел бы отображать пин-код для каждого моего адреса.Для этого я создал JSON с некоторыми местами.До сих пор я только мог получить доступ к этому локальному файлу и создать печать с ним.Но когда я пытаюсь вызвать функцию для создания булавки на карте, появляется ошибка.
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet weak var mapa: MKMapView!
var gerenciadorLocalizacao = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
configurarGerenciadorLocalizacao()
guard let path = Bundle.main.path(forResource: "testeJSON", ofType: "json") else {return}
let url = URL(fileURLWithPath: path)
do {
let data = try Data(contentsOf: url)
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray
print(json)
guard let array = json as? [Any] else {return}
for user in array {
guard let userDict = user as? [String: Any] else {return}
guard let userId = userDict["id"] as? String else {return}
guard let name = userDict["nome"] as? String else {return}
guard let lat = userDict["latitude"] as? String else {return}
guard let lon = userDict["longitude"] as? String else {return}
guard let note = userDict["nota"] as? String else {return}
exibirLocalMapa(latitude: Double(lat)!, longitude: Double(lon)!, titulo: name, nota: note)
print(userId)
print(name)
print(lat)
print(lon)
print(note)
print(" ")
}
}catch {
print(error)
}
}
func exibirLocalMapa(latitude: Double, longitude: Double, titulo: String, nota: String) {
let latitude: CLLocationDegrees = latitude
let longitude: CLLocationDegrees = longitude
let deltaLatitude: CLLocationDegrees = 0.01
let deltaLongitude: CLLocationDegrees = 0.01
let localizacao: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
let areaVisualizacao: MKCoordinateSpan = MKCoordinateSpanMake(deltaLatitude, deltaLongitude)
let regiao: MKCoordinateRegion = MKCoordinateRegionMake(localizacao, areaVisualizacao)
self.mapa.setRegion(regiao, animated: true)
let anotacao = MKPointAnnotation()
//Configurar a anotação
anotacao.coordinate = localizacao
anotacao.title = titulo
anotacao.subtitle = nota
self.mapa.addAnnotation(anotacao)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func configurarGerenciadorLocalizacao(){
gerenciadorLocalizacao.delegate = self
gerenciadorLocalizacao.desiredAccuracy = kCLLocationAccuracyBest
gerenciadorLocalizacao.requestWhenInUseAuthorization()
gerenciadorLocalizacao.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status != .authorizedWhenInUse {
let alertaController = UIAlertController(title: "Permissão de Localização", message: "Necessário permissão para acesso à sua localização. Favor habilitar esta funcionalidade", preferredStyle: .alert)
let acaoConfiguracoes = UIAlertAction(title: "Abrir Configurações", style: .default, handler: {(alertaConfiguracoes) in
if let configuracoes = NSURL(string: UIApplicationOpenSettingsURLString) {
UIApplication.shared.open(configuracoes as URL)
}
})
let acaoCancelar = UIAlertAction(title: "Cancelar", style: .default, handler: nil)
alertaController.addAction(acaoConfiguracoes)
alertaController.addAction(acaoCancelar)
present(alertaController, animated: true, completion: nil)
}
}
}