Ios 如何使用来自服务器的数据创建多个MapKit注释?

Ios 如何使用来自服务器的数据创建多个MapKit注释?,ios,iphone,swift,mapkit,Ios,Iphone,Swift,Mapkit,我一直在地图视图上做多个注释,这真的很困难。到目前为止,我已经能够创建相关的类来下载、解析数据并将其存储到可以使用的数组中。然而,我仍在努力使用上述数据,并做出必要的注释 HomeModel类-从服务器下载并解析所需信息 import UIKit import Foundation protocol HomeModelProtocol: class { func itemsDownloaded(items: NSArray) } class HomeModel: NSObject, URLS

我一直在地图视图上做多个注释,这真的很困难。到目前为止,我已经能够创建相关的类来下载、解析数据并将其存储到可以使用的数组中。然而,我仍在努力使用上述数据,并做出必要的注释

HomeModel类-从服务器下载并解析所需信息

import UIKit
import Foundation

protocol HomeModelProtocol: class {
func itemsDownloaded(items: NSArray)
}

class HomeModel: NSObject, URLSessionDataDelegate {

weak var delegate: HomeModelProtocol!

var data = Data()

let urlPath: String = "https://FAKEDATABASEURL.XYZ"

func downloadItems() {
    let url: URL = URL(string: urlPath)!
    let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
    let task = defaultSession.dataTask(with: url) { (data, response, error) in

        if error != nil {
            print("Failed to download data")
        } else {
            print("Data downloaded")
            self.parseJSON(data!)
        }
    }
    task.resume()
}

func parseJSON(_ data:Data) {

    var jsonResult = NSArray()

    do {
        jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! NSArray
    } catch let error as NSError {
        print(error)
    }

    var jsonElement = NSDictionary()
    let locations = NSMutableArray()

    for i in 0 ..< jsonResult.count {
        jsonElement = jsonResult[i] as! NSDictionary
        let location = LocationModel()

        if let name = jsonElement["Name"] as? String,
           let address = jsonElement["Address"] as? String,
           let latitude = jsonElement["Latitude"] as? String,
           let longitude = jsonElement["Longitude"] as? String {

            location.name = name
            location.address = address
            location.latitude = latitude
            location.longitude = longitude
    }

    locations.add(location)
}
    DispatchQueue.main.async(execute: { ()-> Void in
        self.delegate.itemsDownloaded(items: locations)
    })
}
}
地图视图控制器-控制应用程序的地图

import UIKit
import MapKit
import CoreLocation

class HotPlacesViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

@IBOutlet weak var mapView: MKMapView!
var isFirstTime = true

var locationManager = CLLocationManager()
let newPin = MKPointAnnotation()

var selectedLocation:LocationModel?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    // Setup the location services delegate in this class.
    locationManager.delegate = self

    // This little method requests the users permission for location services whilst in this view controller.
    if CLLocationManager.authorizationStatus() == .notDetermined {
        self.locationManager.requestAlwaysAuthorization()
    let alert = UIAlertController(title: "You can change this option in the Settings App", message: "So keep calm your selection is not permanent. Make your 
let locations = NSMutableArray()
array accessible by other classes so that you can use this array in your
HotPlacesViewController
class.

Then in your
HotPlacesViewController
class declare a property for holding
locations
data. And load the data inside
viewDidLoad()
like:

class HotPlacesViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
    // declare a property which will hold the locations data
    override func viewDidLoad() {
        ...
        ...
        locations = // load your data here
    }
}
导入UIKit
导入地图套件
导入核心定位
类HotPlacesViewController:UIViewController、CLLocationManagerDelegate、MKMapViewDelegate{
@ibvar映射视图:MKMapView!
var isFirstTime=true
var locationManager=CLLocationManager()
设newPin=MKPointAnnotation()
var selectedLocation:LocationModel?
重写func viewDidLoad(){
super.viewDidLoad()
//加载视图后执行任何其他设置。
//在此类中设置location services委托。
locationManager.delegate=self
//此小方法在该视图控制器中请求用户对位置服务的权限。
如果CLLocationManager.authorizationStatus()=未确定{
self.locationManager.requestAlwaysAuthorization()

let alert=UIAlertController(标题:“您可以在设置应用程序中更改此选项”,消息:“请保持冷静您的选择不是永久性的。使您的
let locations=NSMutableArray()
数组可供其他类访问,以便您可以在
HotPlacesViewController
类中使用此数组

然后在
HotPlacesViewController
类中声明一个用于保存
位置
数据的属性,并在
viewDidLoad()中加载数据,如:

for location in locations {
    let annotation = MKPointAnnotation()
    annotation.title = location.name
    annotation.coordinate = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
    mapView.addAnnotation(annotation)

}
然后,对于多个注释,请遵循以下逻辑:


你想从你的
位置
数组加载所有点吗?@Subramanian是的。谢谢你的回答,但是请你完成
位置=
行,因为我想再次检查。请你也可以一步一步地检查,因为我想确保我已经完成了一些步骤。
位置=NSMut对于位置{let annotation=MKPointAnnotation()annotation.title=location.name//中的位置,将纬度和经度值转换为双精度。让lat=Double((selectedLocation?.latitude)!)让long=Double((selectedLocation?.longitude)!)annotation.title=location.name annotation.coordinate=CLLocationCoordinate2D(纬度:纬度!经度:长!)mapView.addAnnotation(注释)}
我已经实现了你的方式,但是当我在我的设备上运行它时,它仍然没有显示所需位置的PIN。嘿@TimmyT我上传了一个。你可以下载它。虽然我从
plist
文件加载了我的位置,而不是从任何
json api
,但我认为你将能够根据需要进行一些修改。
for location in locations {
    let annotation = MKPointAnnotation()
    annotation.title = location.name
    annotation.coordinate = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
    mapView.addAnnotation(annotation)

}