我是Xcode的新手,我从来没有为Swift创建过iPhone的应用程序,所以我对此仍然有很多麻烦。
在我的应用中,我想打开地图页面,并希望为我拥有的每个地址显示一个图钉。为此,我创建了一个带有某些位置的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)
}
}
}
答案 0 :(得分:0)
请按照以下步骤操作,以将所有图钉放在地图上:
您必须使用 for循环从JSON文件中获取所有详细信息,并将其存储在数组中。
调用函数,该函数将使用存储的数组中的纬度,经度,地点名称和注释在地图上标记注释。
快乐编码!
答案 1 :(得分:0)
也许您可以尝试创建自己的扩展MKPointAnnotation的类,然后将JSON的元素映射到该自定义类的数组中,最后调用mapView.addAnnotations(yourAnnotationsArrayHere)。
尝试遵循以下示例: https://www.raywenderlich.com/160517/mapkit-tutorial-getting-started
我建议您从此网站开始进行iOS开发。