#IBAction func addPin(_ sender: UILongPressGestureRecognizer) {
let location = sender.location(in: self.mapView)
let locCoord = self.mapView.convert(location, toCoordinateFrom: self.mapView)
let annotation = MKPointAnnotation()
annotation.coordinate = locCoord
annotation.title = titleTextField.text
var annotationsArray: [[String:Any]]!
var annotationsData = UserDefaults.standard.data(forKey: "StoredAnnotations")
//If the data is nil, then set the new annotation as the only element in the array
if annotationsData == nil {
annotationsArray = [newAnnotationDict]
} else {
//If it isn't nil, then convert the data into an array of dicts
do {
//Convert this data into an array of dicts
annotationsArray = try JSONSerialization.jsonObject(with: annotationsData!, options: []) as! [[String:Any]]
annotationsArray.append(newAnnotationDict)
} catch {
print(error.localizedDescription)
}
}
do {
//Use JSONSerialization to convert the annotationsArray into Data
let jsonData = try JSONSerialization.data(withJSONObject: annotationsArray, options: .prettyPrinted)
//Store this data in UserDefaults
UserDefaults.standard.set(jsonData, forKey: "StoredAnnotations")
} catch {
print(error.localizedDescription)
}
}
#IBAction func deleteLast(sender: UIButton){
}
I am currently creating annotations on a MapView using the code given above. I would like to delete the previous annotation that was created by the user. How would I do this by using the deleteLast button?
Related
I'm using an API to get latitude and longitude coordinates and place them on a map with the name of the place it corresponds to. I'm able to put one place's lat and long coordinates but I'm not too sure how to add all of them to a map. I can't get my head around how to do it. I've tried to use a for loop to do it but I'm too sure on how I would implement it. This is what I've got so far:
func getData() {
let url = "https://www.givefood.org.uk/api/2/foodbanks/"
let task = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: { [self] data, response, error in
guard let data = data, error == nil else {
print("Wrong")
return
}
var result: [Info]?
do {
result = try JSONDecoder().decode([Info].self, from: data)
}
catch {
print("Failed to convert: \(error.localizedDescription)")
}
guard let json = result else {
return
}
for each in json {
var each = 0
each += 1
let comp = json[each].lat_lng?.components(separatedBy: ",")
let latString = comp![each]
let lonString = comp![each]
let lat = Double(latString)
let lon = Double(lonString)
let locationPin: CLLocationCoordinate2D = CLLocationCoordinate2DMake(lat!, lon!)
let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(51.55573, -0.108312)
let region = MKCoordinateRegion.init(center: location, latitudinalMeters: regionInMetres, longitudinalMeters: regionInMetres)
mapView.setRegion(region, animated: true)
let myAn1 = MapPin(title: json[each].name!, locationName: json[each].name!, coordinate: locationPin)
mapView.addAnnotations([myAn1])
}
})
task.resume()
}
Your loop is wrong, each after for is one Info item. The Int index each is pointless and you set it in each iteration to zero so you get always the same coordinate (at index 1).
First of all declare name and lat_lng as non-optional. All records contain both fields.
struct Info : Decodable {
let lat_lng : String
let name : String
}
Second of all for convenience reasons extend CLLocationCoordinate2D to create a coordinate from a string
extension CLLocationCoordinate2D {
init?(string: String) {
let comp = string.components(separatedBy: ",")
guard comp.count == 2, let lat = Double(comp[0]), let lon = Double(comp[1]) else { return nil }
self.init(latitude: lat, longitude: lon )
}
}
Third of all put all good code into the do scope instead of dealing with optionals and set the region once before the loop
func getData() {
let url = "https://www.givefood.org.uk/api/2/foodbanks/"
let task = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: { [self] data, response, error in
if let error = error { print(error); return }
do {
let result = try JSONDecoder().decode([Info].self, from: data!)
let location = CLLocationCoordinate2D(latitude: 51.55573, longitude: -0.108312)
let region = MKCoordinateRegion.init(center: location, latitudinalMeters: regionInMetres, longitudinalMeters: regionInMetres)
mapView.setRegion(region, animated: true)
var pins = [MapPin]()
for info in result {
if let coordinate = CLLocationCoordinate2D(string: info.lat_lng) {
pins.append(MapPin(title: info.name, locationName: info.name, coordinate: coordinate))
}
}
DispatchQueue.main.async {
self.mapView.addAnnotations(pins)
}
}
catch {
print("Failed to convert: \(error)")
}
})
task.resume()
}
I am using the code below to retrieve data from MySQL to show multiple locations on MKMapView using Swift.
The data and locations shows on the map, but what I could not figure out is how to adjust the zoom to cover all locations in that area.
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()
//the following insures none of the JsonElement values are nil through optional binding
if let evIdL = jsonElement["id"] as? String,
let evUserNameL = jsonElement["username"] as? String,
let evNotikindL = jsonElement["notikind"] as? String,
let evLatiL = jsonElement["lati"] as? String,
let evLongiL = jsonElement["longi"] as? String,
let evLocatL = jsonElement["locat"] as? String,
let evTimedateL = jsonElement["timedate"] as? String,
let evDistanceL = jsonElement["distance"] as? String
{
location.evId = evIdL
location.evUsername = evUserNameL
location.evNotikind = evNotikindL
location.evLati = evLatiL
location.evLongi = evLongiL
location.evLocat = evDistanceL
location.evTimedate = evTimedateL
location.evDisatnce = evDistanceL
location.evLocat = evLocatL
// the code to show locations
let latiCon = (location.evLati as NSString).doubleValue
let longiCon = (location.evLongi as NSString).doubleValue
let annotations = locations.map { location -> MKAnnotation in
let annotation = MKPointAnnotation()
annotation.title = evNotikindL
annotation.coordinate = CLLocationCoordinate2D(latitude:latiCon, longitude: longiCon)
return annotation
}
self.map.showAnnotations(annotations, animated: true)
self.map.addAnnotations(annotations)
}
locations.add(location)
}
DispatchQueue.main.async(execute: { () -> Void in
self.itemsDownloaded(items: locations)
})
}
I am using PHP file to connect with MySQL, as I said the code working and showing the locations but the zoom focus on one location only.
You can try
DispatchQueue.main.async {
self.map.addAnnotations(annotations)
self.map.showAnnotations(annotations, animated: true)
// make sure itemsDownloaded needs main ??
self.itemsDownloaded(items: locations)
}
Want to draw a PolyLine from userLocation to multiple marker. In my code already added markers coordinates in a array then added userLocation into 0th position of that array. Now I want to draw a route polyLine between array elements. My code is given below...
self.coods.append(self.currentLocation)
let jsonResponse = response.data
do{
let json = try JSON(data: jsonResponse!)
self.dictXYZ = [json]
print("JsonResponse printed \(json["data"][0]["lattitude"])")
if let array = json["data"].array{
for i in 0..<array.count{
var coordinate = CLLocationCoordinate2D()
coordinate.latitude = array[i]["lattitude"].doubleValue
coordinate.longitude = array[i]["longitude"].doubleValue
self.coods.append(coordinate)
}
for j in self.coods {
let marker = GMSMarker()
marker.position = j
let camera = GMSCameraPosition.camera(withLatitude: j.latitude, longitude: j.longitude, zoom: 12)
self.mapView.camera = camera
marker.map = self.mapView
}
let path = GMSMutablePath()
for j in self.coods {
path.add(j)
}
let polyline = GMSPolyline(path: path)
polyline.map = mapView
In the Google Developer Docs.
Waypoints - Specifies an array of intermediate locations to include along the route between the origin and destination points as
pass through or stopover locations. Waypoints alter a route by
directing it through the specified location(s). The API supports
waypoints for these travel modes: driving, walking and bicycling; not
transit.
First you need to create a waypoints for all intermediate locations to add the route between the source and destination. With that polyline you can create a GMSPath and then draw the route by using GMSPolyline. I hope below solution can help you to draw a route for multiple locations.
func getPolylineRoute(from source: CLLocationCoordinate2D, to destinations: [CLLocationCoordinate2D], completionHandler: #escaping (Bool, String) -> ()) {
guard let destination = destinations.last else {
return
}
var wayPoints = ""
for (index, point) in destinations.enumerated() {
if index == 0 { // Skipping first location that is current location.
continue.
}
wayPoints = wayPoints.count == 0 ? "\(point.latitude),\(point.longitude)" : "\(wayPoints)%7C\(point.latitude),\(point.longitude)"
}
let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(source.latitude),\(source.longitude)&destination=\(destination.latitude),\(destination.longitude)&sensor=true&mode=driving&waypoints=\(wayPoints)&key=\(GOOGLE_API_KEY)")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print("Failed : \(String(describing: error?.localizedDescription))")
return
} else {
do {
if let json: [String: Any] = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] {
guard let routes = json["routes"] as? [[String: Any]] else { return }
if (routes.count > 0) {
let overview_polyline = routes[0]
let dictPolyline = overview_polyline["overview_polyline"] as? NSDictionary
let points = dictPolyline?.object(forKey: "points") as? String
completionHandler(true, points!)
} else {
completionHandler(false, "")
}
}
} catch {
print("Error : \(error)")
}
}
}
task.resume()
}
Pass the current location and destination array of locations to getPolylineRoute method. Then call the drawPolyline method with polyline points from main thread.
getPolylineRoute(from: coods[0], to: coods) { (isSuccess, polylinePoints) in
if isSuccess {
DispatchQueue.main.async {
self.drawPolyline(withMapView: self.mapView, withPolylinePoints: polylinePoints)
}
} else {
print("Falied to draw polyline")
}
}
func drawPolyline(withMapView googleMapView: GMSMapView, withPolylinePoints polylinePoints: String){
path = GMSPath(fromEncodedPath: polylinePoints)!
let polyline = GMSPolyline(path: path)
polyline.strokeWidth = 3.0
polyline.strokeColor = .lightGray
polyline.map = googleMapView
}
First create GMSPath object
let path = GMSMutablePath()
self.coods.forEach {
path.add(coordinate: $0)
}
https://developers.google.com/maps/documentation/ios-sdk/reference/interface_g_m_s_mutable_path.html#af62038ea1a9da3faa7807b8d22e72ffb
Then Create GMSPolyline object using path
let pathLine = GMSPolyline.with(path: path)
pathLine.map = self.mapView
https://developers.google.com/maps/documentation/ios-sdk/reference/interface_g_m_s_polyline.html#ace1dd6e6bab9295b3423712d2eed90a4
import UIKit
import MapKit
import CoreLocation
import AddressBook
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
#IBOutlet weak var TheMap: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
zoomToRegion()
location()
}
func centerMapOnLocation(location: MKPointAnnotation, regionRadius: Double) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius * 2.0, regionRadius * 2.0)
TheMap.setRegion(coordinateRegion, animated: true)
}
//MARK:- MapViewDelegate methods
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let polylineRenderer = MKPolylineRenderer(overlay: overlay)
if overlay is MKPolyline {
polylineRenderer.strokeColor = UIColor.blue
polylineRenderer.lineWidth = 5
}
return polylineRenderer
}
//MARK:- Zoom to region
func zoomToRegion() {
let location = CLLocationCoordinate2D(latitude: 28.618945, longitude: 77.377347400000005)
let region = MKCoordinateRegionMakeWithDistance(location, 5000.0, 7000.0)
TheMap.setRegion(region, animated: true)
}
// API CALL FUNCTION
func location() {
let user = "userid"
let password = "password"
let postString = ["empid":user, "date1": password]
var request = URLRequest(url:URL(string: "http://mydomainhere.com/airtel_hrm/webapi/api/getpunchdeytails")!)
request.httpMethod = "POST"
request.httpBody = try! JSONSerialization.data(withJSONObject: postString, options:.prettyPrinted)
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?)in
if error != nil
{
print("error=\(error)")
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any],
let data = json["punchdetails"] as? [[String: Any]] {
//print(data)
for datas in data {
let lat = datas["punch_loc_lat"] as! String
let long = datas["punch_loc_long"] as! String
var annotations = [MKPointAnnotation]()
let latitude = CLLocationDegrees(lat)
let longitude = CLLocationDegrees(long)
let coordinate = CLLocationCoordinate2D(latitude: latitude!, longitude: longitude!)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotations.append(annotation)
self.TheMap.addAnnotations(annotations)
self.TheMap.delegate = self
self.centerMapOnLocation(location: annotations[0], regionRadius: 2000.0)
// Connect all the mappoints using Poly line.
var points: [CLLocationCoordinate2D] = [coordinate] //[CLLocationCoordinate2D]()
for annotation in annotations {
points.append(annotation.coordinate)
}
print("this is points = \(points)")
let polyline = MKPolyline(coordinates: &points, count: points.count)
//self.TheMap.add(polyline)
} //for loop closed
}
} catch {
print(error)
}
}
task.resume()
}
}
I'm sure if you shared the results of the print statement, the problem would have been obvious. You're probably seeing lots of print statements. Bottom line, you should define your array outside of the for loop, only append values within the loop, and then add the polyline after the loop:
do {
if let json = try JSONSerialization.jsonObject(with: data!) as? [String: Any],
let data = json["punchdetails"] as? [[String: Any]] {
var annotations = [MKPointAnnotation]()
for datas in data {
let lat = datas["punch_loc_lat"] as! String
let long = datas["punch_loc_long"] as! String
let latitude = CLLocationDegrees(lat)
let longitude = CLLocationDegrees(long)
let coordinate = CLLocationCoordinate2D(latitude: latitude!, longitude: longitude!)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotations.append(annotation)
}
self.TheMap.delegate = self // you really should do this in IB or, if you feel compelled to do it programmatically, in viewDidLoad
// Connect all the mappoints using Poly line.
let points = annotations.map { $0.coordinate }
print("this is points = \(points)")
let polyline = MKPolyline(coordinates: &points, count: points.count)
DispatchQueue.main.async {
self.centerMapOnLocation(location: annotations[0], regionRadius: 2000.0)
self.TheMap.addAnnotations(annotations)
self.TheMap.add(polyline)
}
}
} catch {
print(error)
}
Note, I'd also do all interaction with the map view from the main queue.
My app working with Geojson file. I use MapBox SDK to add MGLPolyline to map. But the problem is my file too large, so that the app crash and got the error: Message from debugger: Terminated due to memory issue. I faced with 66234 objects at first loop. I tried to chunk the array to new array but not success. Please help me to solve the prolem. Here is my code for draw on map and here is my test project on github use Xcode 8.1 If have any different 3rd party which can solve my prolems is welcome too:
func drawPolyline() {
// Parsing GeoJSON can be CPU intensive, do it on a background thread
DispatchQueue.global(qos: .background).async {
// Get the path for example.geojson in the app's bundle
let jsonPath = Bundle.main.path(forResource: "KMLMAPNew", ofType: "json")
let jsonData = NSData(contentsOfFile: jsonPath!)
do {
// Load and serialize the GeoJSON into a dictionary filled with properly-typed objects
guard let jsonDict = try JSONSerialization.jsonObject(with: jsonData! as Data, options: []) as? Dictionary<String, AnyObject>, let features = jsonDict["features"] as? Array<AnyObject> else{return}
for feature in features {
guard let feature = feature as? Dictionary<String, AnyObject>, let geometry = feature["geometry"] as? Dictionary<String, AnyObject> else{ continue }
if geometry["type"] as? String == "LineString" {
// Create an array to hold the formatted coordinates for our line
var coordinates: [CLLocationCoordinate2D] = []
if let locations = geometry["coordinates"] as? Array<AnyObject> {
// Iterate over line coordinates, stored in GeoJSON as many lng, lat arrays
for location in locations {
// Make a CLLocationCoordinate2D with the lat, lng
if let location = location as? Array<AnyObject>{
let coordinate = CLLocationCoordinate2DMake(location[1].doubleValue, location[0].doubleValue)
// Add coordinate to coordinates array
coordinates.append(coordinate)
}
}
}
let line = MGLPolyline(coordinates: &coordinates, count: UInt(coordinates.count))
// Optionally set the title of the polyline, which can be used for:
// - Callout view
// - Object identification
line.title = "Crema to Council Crest"
// Add the annotation on the main thread
DispatchQueue.main.async {
// Unowned reference to self to prevent retain cycle
[unowned self] in
self.mapboxView.addAnnotation(line)
}
}
}
}
catch
{
print("GeoJSON parsing failed")
}
}
}
EDIT::#Alessandro Ornano and #fragilecat thanks so much. But those solutions still cannot solve the terminate of the app on iPad. I think it so hard to change the current code to get it to work properly, because the data is so large. I think I will need another solution that works with big data. Like chunking the array into the small arrays then loading them by queue. But I don't know how to start :(
I send an email to the support team at MapBox, asking for suggestions.
One thing I have learnt from creating memory intensive apps is that you have to use autoreleasepool every time you create variables inside loops, if these loops are long
Review all your code and transform things like
func loopALot() {
for _ in 0 ..< 5000 {
let image = NSImage(contentsOfFile: filename)
}
}
into
func loopALot() {
for _ in 0 ..< 5000 {
autoreleasepool {
let image = NSImage(contentsOfFile: filename)
}
}
}
Review all kinds of loops for, while, etc.
This will force of iOS to release the variable and its correspondent memory usage at the end of every turn of the loop, instead of holding the variable and its memory usage until the function ends. That will reduce dramatically your memory usage.
The problem here is related to effective memory management. You are loading a lot of data via your json file. You realized that you needed to do the majority of the work on a background queue (thread) however the issue is how you are updating the UI via DispatchQueue.main.async function. In the current version of the drawPolyline() method you are switching between the background queue and the main queue 66234 times, given the number of objects in your first loop. Also you were creating the same number of CLLocationCoordinate2D arrays.
This leads to a huge memory footprint. You do not mention any requirements in regards to how you render the lines. So if we restructure your drawPolyline() method to use a instance variable for the CLLocationCoordinate2D array so we only use one and then we process all of the json file before we update the UI. The memory usage dropped down to a some what more manageable 664.6 MB.
Of course the rendering may not be exactly what you are looking for and if that's the case you might want to restructure your CLLocationCoordinate2D array into a more suitable data structure.
Below is your ViewController class with the rewritten drawPolyline() as drawPolyline2()
import UIKit
import Mapbox
class ViewController: UIViewController, MGLMapViewDelegate {
#IBOutlet var mapboxView: MGLMapView!
fileprivate var coordinates = [[CLLocationCoordinate2D]]()
fileprivate var jsonData: NSData?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
mapboxView = MGLMapView(frame: view.bounds)
mapboxView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
// mapboxView.setCenter(CLLocationCoordinate2D(latitude: 45.5076, longitude: -122.6736),
// zoomLevel: 11, animated: false)
mapboxView.setCenter(CLLocationCoordinate2D(latitude: 1.290270, longitude: 103.851959),
zoomLevel: 11, animated: false)
view.addSubview(self.mapboxView)
mapboxView.delegate = self
mapboxView.allowsZooming = true
drawPolyline2()
//newWay()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func drawPolyline2() {
DispatchQueue.global(qos: .background).async {
if let path = Bundle.main.path(forResource: "KMLMAPNew", ofType: "json") {
let fileURL = URL(fileURLWithPath: path)
if let data = try? Data(contentsOf: fileURL) {
do {
let dictionary = try JSONSerialization.jsonObject(with: data as Data, options: []) as? Dictionary<String, AnyObject>
if let features = dictionary?["features"] as? Array<AnyObject> {
print("** START **")
for feature in features {
guard let feature = feature as? Dictionary<String, AnyObject>, let geometry = feature["geometry"] as? Dictionary<String, AnyObject> else { continue }
if geometry["type"] as? String == "LineString" {
// Create an array to hold the formatted coordinates for our line
if let locations = geometry["coordinates"] as? Array<AnyObject> {
// Iterate over line coordinates, stored in GeoJSON as many lng, lat arrays
var featureCoordinates = [CLLocationCoordinate2D]()
for location in locations {
// Make a CLLocationCoordinate2D with the lat, lng
if let location = location as? Array<AnyObject>{
let coordinate = CLLocationCoordinate2DMake(location[1].doubleValue, location[0].doubleValue)
// Add coordinate to coordinates array
featureCoordinates.append(coordinate)
}
}
// Uncomment if you need to store for later use.
//self.coordinates.append(featureCoordinates)
DispatchQueue.main.async {
let line = MGLPolyline(coordinates: &featureCoordinates, count: UInt(featureCoordinates.count))
// Optionally set the title of the polyline, which can be used for:
// - Callout view
// - Object identification
line.title = "Crema to Council Crest"
self.mapboxView.addAnnotation(line)
}
}
}
}
print("** FINISH **")
}
} catch {
print("GeoJSON parsing failed")
}
}
}
}
}
func drawSmallListObj(list: [Dictionary<String, AnyObject>]){
for obj in list{
// print(obj)
if let feature = obj as? Dictionary<String, AnyObject> {
if let geometry = feature["geometry"] as? Dictionary<String, AnyObject> {
if geometry["type"] as? String == "LineString" {
// Create an array to hold the formatted coordinates for our line
var coordinates: [CLLocationCoordinate2D] = []
if let locations = geometry["coordinates"] as? Array<AnyObject> {
// Iterate over line coordinates, stored in GeoJSON as many lng, lat arrays
for location in locations {
// Make a CLLocationCoordinate2D with the lat, lng
if let location = location as? Array<AnyObject>{
let coordinate = CLLocationCoordinate2DMake(location[1].doubleValue, location[0].doubleValue)
// Add coordinate to coordinates array
coordinates.append(coordinate)
}
}
}
let line = MGLPolyline(coordinates: &coordinates, count: UInt(coordinates.count))
// Optionally set the title of the polyline, which can be used for:
// - Callout view
// - Object identification
line.title = "Crema to Council Crest"
// Add the annotation on the main thread
DispatchQueue.main.async {
// Unowned reference to self to prevent retain cycle
[unowned self] in
self.mapboxView.addAnnotation(line)
}
}
}
}
}
}
func mapView(_ mapView: MGLMapView, alphaForShapeAnnotation annotation: MGLShape) -> CGFloat {
// Set the alpha for all shape annotations to 1 (full opacity)
return 1
}
func mapView(_ mapView: MGLMapView, lineWidthForPolylineAnnotation annotation: MGLPolyline) -> CGFloat {
// Set the line width for polyline annotations
return 2.0
}
func mapView(_ mapView: MGLMapView, strokeColorForShapeAnnotation annotation: MGLShape) -> UIColor {
// Give our polyline a unique color by checking for its `title` property
if (annotation.title == "Crema to Council Crest" && annotation is MGLPolyline) {
// Mapbox cyan
return UIColor(red: 59/255, green:178/255, blue:208/255, alpha:1)
}
else
{
return UIColor.red
}
}
}
I had some problems to test your project with pods, so I've directly remove pods and use Mapbox framework directly from here.
I've no problems for the first launches both in simulator and real iPad (my iPad 4 gen.) but after a while I've your same error, so I've correct this code with:
DispatchQueue.main.async {
// weaked reference to self to prevent retain cycle
[weak self] in
guard let strongSelf = self else { return }
strongSelf.mapboxView.addAnnotation(line)
}
because unowned it's not enough to prevent retain cycle.
Now seems it works well.
Hope it helps.
P.S. (I've used the latest available Mapbox v3.3.6)
Update (after comments):
So, first of all I make all my test with Mapbox framework inserted as "embedded framework".
I've make some corrections to your github project only to ViewController.swift to avoid retain cycles.
P.S. I remove comments lines to make easy reading:
func drawPolyline() {
DispatchQueue.global(qos: .background).async {
[weak self] in
guard let strongSelf = self else { return }
let jsonPath = Bundle.main.path(forResource: "KMLMAPNew", ofType: "json")
let jsonData = NSData(contentsOfFile: jsonPath!)
do {
guard let jsonDict = try JSONSerialization.jsonObject(with: jsonData! as Data, options: []) as? Dictionary<String, AnyObject>, let features = jsonDict["features"] as? Array<AnyObject> else{return}
for feature in features {
guard let feature = feature as? Dictionary<String, AnyObject>, let geometry = feature["geometry"] as? Dictionary<String, AnyObject> else{ continue }
if geometry["type"] as? String == "LineString" {
var coordinates: [CLLocationCoordinate2D] = []
if let locations = geometry["coordinates"] as? Array<AnyObject> {
for location in locations {
if let location = location as? Array<AnyObject>{
let coordinate = CLLocationCoordinate2DMake(location[1].doubleValue, location[0].doubleValue)
coordinates.append(coordinate)
}
}
}
let line = MGLPolyline(coordinates: &coordinates, count: UInt(coordinates.count))
line.title = "Crema to Council Crest"
print(feature) // Added this line just for debug to see the flow..
DispatchQueue.main.async {
strongSelf.mapboxView.addAnnotation(line)
}
}
}
}
catch
{
print("GeoJSON parsing failed")
}
}
}
func newWay(){
DispatchQueue.global(qos: .background).async {
[weak self] in
guard let strongSelf = self else { return }
let jsonPath = Bundle.main.path(forResource: "KMLMAPNew", ofType: "json")
let jsonData = NSData(contentsOfFile: jsonPath!)
do {
if let jsonDict = try JSONSerialization.jsonObject(with: jsonData! as Data, options: []) as? Dictionary<String, AnyObject> {
if let features = jsonDict["features"] as? Array<AnyObject> {
let chunks = stride(from: 0, to: features.count, by: 2).map {
Array(features[$0..<min($0 + 2, features.count)])
}
for obj in chunks{
strongSelf.drawSmallListObj(list: obj as! [Dictionary<String, AnyObject>])
}
}
}
}
catch
{
print("GeoJSON parsing failed")
}
}
}
func drawSmallListObj(list: [Dictionary<String, AnyObject>]){
for obj in list{
if let feature = obj as? Dictionary<String, AnyObject> {
if let geometry = feature["geometry"] as? Dictionary<String, AnyObject> {
if geometry["type"] as? String == "LineString" {
var coordinates: [CLLocationCoordinate2D] = []
if let locations = geometry["coordinates"] as? Array<AnyObject> {
for location in locations {
if let location = location as? Array<AnyObject>{
let coordinate = CLLocationCoordinate2DMake(location[1].doubleValue, location[0].doubleValue)
coordinates.append(coordinate)
}
}
}
let line = MGLPolyline(coordinates: &coordinates, count: UInt(coordinates.count))
line.title = "Crema to Council Crest"
DispatchQueue.main.async {
[weak self] in
guard let strongSelf = self else { return }
strongSelf.mapboxView.addAnnotation(line)
}
}
}
}
}
}
Will share my experience with this strange issue.
For me the app crashed with "Message from debugger: Terminated due to memory issue" and instruments didn't help a lot. As well the Memory - was within the green limits. So I was not sure what is causing that. And it was not possible to debug, and single-device specific issue.
Just restarted the iPhone 6 - and the issue disappeared for now.
First Solution
Maybe your for loop is running infinitely and allocating memory to an array with nil value every time. It is using high amounts of memory, so it gives this error.
Please check by print something in the for loop.
Second Solution
Add this in didReceiveMemoryWarning:
NSURLCache.sharedURLCache().removeAllCachedResponses()
NSURLCache.sharedURLCache().diskCapacity = 0
NSURLCache.sharedURLCache().memoryCapacity = 0
You can also change the cache policy of the NSURLRequest:
let day_url = NSURL(string: "http://www.example.com")
let day_url_request = NSURLRequest(URL: day_url,
cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: 10.0)
let day_webView = UIWebView()
day_webView.loadRequest(day_url_request)
More information on cache policies here.
make you stuff on callout this means execute polyne only when click on the pin
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView)
I was receiving this error and was very confused since my app's memory usage was fairly small.
In the end, I discovered that it was due to me loading a number of files as mapped memory, e.g:
let data = try Data(contentsOf: url, options: .mappedIfSafe)
I don't know why I was getting these bizarre crashes, but just loading the data normally prevented the crashes from happening.