I'm new in Xcode and I've never created an app for the iphone with the swift, so I still have a lot of trouble with this.
In my app I want to open the map page and would like to appear a pin for every address I have. For this I created a json with some locations. So far I've only been able to access this local file and generate a print with it. But when I try to call the function to create the pin on the map an error appears.
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)
}
}
}
Follow below steps in order to drop all pins on map:
You have to fetch all the details from the JSON file using for loop and store it in array.
Call function which will mark annotation on map using latitude, longitude, name of the place and note from the stored array.
Happy Coding!