Terminating app due to uncaught exception 'NSRangeException'. libc++abi.dylib: terminating with uncaught exception of type NSException - ios

I get this crash error:
MXNet2CoreML[11383:1168377]
*** Terminating app due to uncaught exception 'NSRangeException', reason:
*** -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray'
*** First throw call stack: (0x18333f164 0x182588528 0x18329a020 0x1007894bc 0x1011ef94c 0x1011b0420 0x1021412cc 0x10214128c
0x102145ea0 0x1832e7344 0x1832e4f20 0x183204c58 0x1850b0f84
0x18c95d5c4 0x1007d8894 0x182d2456c)
libc++abi.dylib: terminating with uncaught exception of type
NSException
Here is the Complete Code
//Owais: - Map setup
func resetRegion(){
let region = MKCoordinateRegionMakeWithDistance(annotation.coordinate, 5000, 5000)
mapKit.setRegion(region, animated: true)
}
var myLatitude = ""
var myLongitude = ""
// Array of annotations
let annotation = MKPointAnnotation()
var places = PredictionLocationList().place
var locationsArray = [String]()
var ie: Int = 0
#IBOutlet var mapKit: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
let defaults = UserDefaults.standard
let data = defaults.data(forKey: "selectedimage")
let uiimage2 = UIImage(data: data!)
defaults.synchronize()
let image = uiimage2
// imageView.image = image
predictUsingVision(image: image!)
let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGesture))
swipeDown.direction = UISwipeGestureRecognizerDirection.down
self.view.addGestureRecognizer(swipeDown)
// Do any additional setup after loading the view.
}
#objc func respondToSwipeGesture(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.right:
print("Swiped right")
case UISwipeGestureRecognizerDirection.down:
print("Swiped down")
self.dismiss(animated: true, completion: nil)
case UISwipeGestureRecognizerDirection.left:
print("Swiped left")
case UISwipeGestureRecognizerDirection.up:
print("Swiped up")
default:
break
}
}
}
func predictUsingVision(image: UIImage) {
guard let visionModel = try? VNCoreMLModel(for: model.model) else {
fatalError("Something went wrong")
}
let request = VNCoreMLRequest(model: visionModel) { request, error in
if let observations = request.results as? [VNClassificationObservation] {
let top3 = observations.prefix(through: 2)
.map { ($0.identifier, Double($0.confidence)) }
self.show(results: top3)
}
}
request.imageCropAndScaleOption = .centerCrop
let handler = VNImageRequestHandler(cgImage: image.cgImage!)
try? handler.perform([request])
}
typealias Prediction = (String, Double)
func show(results: [Prediction]) {
var s: [String] = []
for (i, pred) in results.enumerated() {
let latLongArr = pred.0.components(separatedBy: "\t")
print("lat long \(latLongArr)")
myLatitude = latLongArr[1]
myLongitude = latLongArr[2]
ie = i
s.append(String(format: "%d: %# %# (%.2f%%)", i + 1, myLatitude, myLongitude, pred.1 * 100))
LocationByCoordinates(latitude: myLatitude, longitude: myLongitude)
// let ew1 = (String(format: "%.2f%", pred.1 * 100))
// print(ew1)
// let double1 = Double(ew1)
// self.doubles.append(double1!)
// print("eueue \(self.doubles)")
// let maxDouble = max(max(double1, double2), double3)
print("first latidue \(myLatitude),,,, \(myLongitude)")
places[i].title = String(i+1)
places[i].coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(myLatitude)!, longitude: CLLocationDegrees(myLongitude)!)
}
// predictionLabel.text = s.joined(separator: "\n")
// Map reset
resetRegion()
mapKit.centerCoordinate = places[0].coordinate
// Show annotations for the predictions on the map
mapKit.addAnnotations(places)
// Zoom map to fit all annotations
zoomMapFitAnnotations()
}
func zoomMapFitAnnotations() {
var zoomRect = MKMapRectNull
for annotation in mapKit.annotations {
let annotationPoint = MKMapPointForCoordinate(annotation.coordinate)
let pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0, 0)
if (MKMapRectIsNull(zoomRect)) {
zoomRect = pointRect
} else {
zoomRect = MKMapRectUnion(zoomRect, pointRect)
}
}
self.mapKit.setVisibleMapRect(zoomRect, edgePadding: UIEdgeInsetsMake(50, 50, 50, 50), animated: true)
}
func LocationByCoordinates (latitude: String,longitude:String) {
let mapsKey = UserDefaults.standard.string(forKey: "maps_key") ?? ""
Alamofire.request("https://maps.googleapis.com/maps/api/geocode/json?latlng=\(latitude),\(longitude)&key=\(mapsKey)").responseJSON { response in
if let json = response.result.value {
let request = json as? NSDictionary
if let id = request!["results"] {
// print(id)
let ide = id as? NSArray
let formatted_address = ide![0]
let fors = formatted_address as! NSDictionary
//print(fors.value(forKey: "formatted_address"))
let forss = fors.value(forKey: "formatted_address")
self.locationsArray.append(forss as? String ?? "")
if self.ie == 0 {
self.places[0].identifier = (forss as? String)!
} else if self.ie == 1 {
self.places[1].identifier = (forss as? String)!
} else if self.ie == 2 {
self.places[2].identifier = (forss as? String)!
}
}
}
}
}
}
extension Collection where Indices.Iterator.Element == Index {
subscript (safe index: Index) -> Iterator.Element? {
return indices.contains(index) ? self[index] : nil
}
}

The problem is in this line let formatted_address = ide![0]
If an array is empty, you can't get it's first element with [0] because there is no element at all!
All you have to do is check if the array is not empty before unwrapping it:
if ide!.count > 0 {
//Your code
}
To avoid force-unwrapping ide, you may want to use optional binding like so:
if let id = request!["results"], let ide = id as? NSArray {
let formatted_address = ide[0]
let fors = formatted_address as! NSDictionary
//rest of your code
}

Related

Google map showing skin color screen

Viewdidload method
override func viewDidLoad() {
super.viewDidLoad()
selectedAdressType = "pickup"
mapV.delegate = self
styleOfMap()
mapV.settings.myLocationButton = true
mapV.isMyLocationEnabled = true
// self.pickupAddressTxtF.setLeftPaddingPoints(7)
//self.destinationAddressTxtF.setLeftPaddingPoints(7)
googleLocationTableV.rowHeight = UITableViewAutomaticDimension
googleLocationTableV.estimatedRowHeight = 50
googleLocationTableV.tableFooterView = UIView(frame: .zero)
savedLocationTableV.keyboardDismissMode = .interactive
googleLocationTableV.keyboardDismissMode = .interactive
// Add footer for set pinn location
googleLocationTableV.tableFooterView = AddFooterView()
savedLocationTableV.tableFooterView = AddFooterView()
redirectMap(to: Double("\(latitude)") ?? 0.0, lng: Double("\(longitude)") ?? 0.0)
let userDefaults = UserDefaults.standard
if userDefaults.object(forKey: "LocationInitialData") != nil {
let retriveArrayData = UserDefaults.standard.object(forKey: "LocationInitialData") as? NSData
let dataDic = (NSKeyedUnarchiver.unarchiveObject(with: retriveArrayData! as Data) as? NSDictionary)
print(" saved response = \(dataDic!)")
self.recentSerchList = dataDic?.value(forKey: "recent_search")as! NSArray
self.savedLocationList = dataDic?.value(forKey: "save_address")as! NSArray
self.savedLocationTableV.reloadData()
}
savedLocationTableV.keyboardDismissMode = .onDrag
googleLocationTableV.keyboardDismissMode = .onDrag
// addressSerachApiCall()
if Language.isRTL {
pickupAddressTxtF.textAlignment = .right
}
}
Redirect Method
func redirectMap(to lat: Double, lng: Double) {
// [_mapView clear];
let position: CLLocationCoordinate2D = CLLocationCoordinate2DMake(lat, lng)
let camera = GMSCameraPosition(target: position, zoom: 16, bearing: 0, viewingAngle: 0)
mapV.animate(to: camera)
}
Styling of map show "Unable to find style.json"
func styleOfMap() {
do {
if let styleURL = Bundle.main.url(forResource: "style", withExtension: "json") {
mapV.mapStyle = try GMSMapStyle(contentsOfFileURL: styleURL)
} else {
NSLog("Unable to find style.json")
}
} catch {
NSLog("One or more of the map styles failed to load. \(error)")
}
}

Problem with MapBox PointAnnotations with data from Alamofire

In my app I need to get annotations coordinates from server, so im getting is with Alamofire request. And when I try to add annotations to map from Alamofire pid im getting unknown error
class MapViewController : UIViewController, MGLMapViewDelegate, FloatingPanelControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
....
....
getDataFromServer()
}
func getDataFromServer() {
let coffeeShopsJSON = AF.request("http://194.6*******")
coffeeShopsJSON.responseJSON { response in
switch response.result {
case .success(let value):
let jsonFile = JSON(value)
let arrayCount = jsonFile.array?.count ?? 0
var id = [Int]()
var name = [String]()
var lat = [Double]()
var lon = [Double]()
var img = [UIImage(named : "cofShopIcon"), UIImage(named : "cofShopIcon"), UIImage(named : "cofShopIcon"), UIImage(named : "cofShopIcon"), UIImage(named : "cofShopIcon")] //test images
for i in 0..<arrayCount {
let j_id = jsonFile[i]["id"].string ?? "-1"
id.append(Int(j_id) ?? -1)
let j_name = jsonFile[i]["name"].string ?? "N/A"
name.append(j_name)
let j_lat = jsonFile[i]["coordX"].string ?? "-1.0"
lat.append(Double(j_lat) ?? -1.0)
let j_lon = jsonFile[i]["coordY"].string ?? "-1.0"
lon.append(Double(j_lon) ?? -1.0)
}
for i in 0..<id.count {
mapData.append(coffeeShopsData(shopId : id[i], name : name[i], icon : img[i], latitude : lat[i], longitude : lon[i]))
}
for i in 0..<mapData.count {
let point = MGLPointAnnotation()
point.coordinate = CLLocationCoordinate2D(latitude : mapData[i].latitude ?? 0, longitude : mapData[i].longitude ?? 0)
point.title = mapData[i].name ?? "*Data Error*"
markers.append(point)
}
self.mapView.addAnnotations(markers)
case .failure(let error):
print(error)
}
}
}
}
Error:
libc++abi.dylib: terminating with uncaught exception of type std::domain_error
I'm new in swift, so any advice will be useful

NSMetadataQuery isUpdating breaks after Reachability changes to none Swift 4

I have coded a UIViewController that handles the upload (Only) for files to iCloud. So far it works well but I was trying to make it better with Network Changes using Reachability.
The way I handle the changes is:
lazy var searchQuery:NSMetadataQuery = {
let searchQueryTemp = NSMetadataQuery()
searchQueryTemp.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]
let searchPredicate = NSPredicate.init(format: "%K BEGINSWITH %# && NOT %K.pathExtension = ''", argumentArray: [NSMetadataItemPathKey,trackFileManager.appICloudExportedMusic!.path,NSMetadataItemFSNameKey])
searchQueryTemp.predicate = searchPredicate
return searchQueryTemp
}()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("\(logClassName): viewWillAppear")
appDelegate.appReachabilityDelegate = self
NotificationCenter.default.addObserver(self, selector: #selector(updateDataWithNotification), name: NSNotification.Name.NSMetadataQueryDidFinishGathering, object: searchQuery)
NotificationCenter.default.addObserver(self, selector: #selector(updateDataWithNotification), name: NSNotification.Name.NSMetadataQueryDidUpdate, object: searchQuery)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
updateSearch()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print("\(logClassName): viewWillDisappear")
NotificationCenter.default.removeObserver(self)
}
#objc func updateDataWithNotification(notification: NSNotification){
print("\(logClassName): updateDataWithNotification \(searchQuery.results.count)")
if let queryObject = notification.object as? NSMetadataQuery{
if searchQuery == queryObject{
print("\(logClassName): Query count = \(queryObject.results.count)")
var iCloudAlbumArrayTemp = [FileIcloudAlbumHeader]()
/* Get the query results [URL] only files */
for result in queryObject.results{
/* Get Metadata for file */
if let metadataItem = result as? NSMetadataItem{
if let urlItem:URL = metadataItem.value(forKey: NSMetadataUbiquitousItemURLInLocalContainerKey) as? URL{
if var urlItemPath = urlItem.path.components(separatedBy: "Exported Music").last{
urlItemPath = String(urlItemPath.dropFirst())
let urlItemArray = urlItemPath.components(separatedBy: "/")
if urlItemArray.count == 3{
var albumICloudTrack = AlbumICloudTrack(url: urlItem)
let isUpdated:Bool = metadataItem.value(forKey: NSMetadataUbiquitousItemIsUploadedKey) as! Bool
let isUpdating: Bool = metadataItem.value(forKey: NSMetadataUbiquitousItemIsUploadingKey) as! Bool
let isDownloading:Bool = metadataItem.value(forKey: NSMetadataUbiquitousItemIsDownloadingKey) as! Bool
if isUpdated{
albumICloudTrack.status = .available
}
else{
if isUpdating{
let perInt = Int(metadataItem.value(forKey: NSMetadataUbiquitousItemPercentUploadedKey) as! Double)
print("\(logClassName): isUpdating: PerInt = \(perInt)")
let perDouble = metadataItem.value(forKey: NSMetadataUbiquitousItemPercentUploadedKey) as! Double
print("\(logClassName): isUpdating: PerInt = \(perDouble)")
albumICloudTrack.percentatge = Int(metadataItem.value(forKey: NSMetadataUbiquitousItemPercentUploadedKey) as! Double)
albumICloudTrack.status = .updating
}
else if isDownloading{
albumICloudTrack.status = .downloading
}
else{
albumICloudTrack.status = .notAvailable
}
}
/* Find Album */
var tempUrl = urlItem.deletingLastPathComponent()
let albumName = tempUrl.lastPathComponent
tempUrl = tempUrl.deletingLastPathComponent()
let artistName = tempUrl.lastPathComponent
//print("\(logClassName): Artist Name = \(artistName) && Album Name = \(albumName)")
let albumHeaderInex = findAlbumHeader(withArtistName: artistName, andAlbum: albumName, in: iCloudAlbumArrayTemp)
if albumHeaderInex != -1{
//print("\(logClassName): Appending Already exists")
iCloudAlbumArrayTemp[albumHeaderInex].urlTrackArray.append(albumICloudTrack)
}
else{
//print("\(logClassName): Creating New Header Album")
var albumHeader = FileIcloudAlbumHeader(artistName: artistName, albumName: albumName, url: urlItem.deletingLastPathComponent())
albumHeader.urlTrackArray.append(albumICloudTrack)
iCloudAlbumArrayTemp.append(albumHeader)
}
}
else{
print("\(logClassName): Discarting Item = \(urlItemPath)")
}
}
}
}
}
/* Copy content for updating Expanded status */
for iCloudAlbumIndex in iCloudAlbumArray.indices{
for iCloudAlbumTempIndex in iCloudAlbumArrayTemp.indices{
if iCloudAlbumArray[iCloudAlbumIndex].artistName == iCloudAlbumArrayTemp[iCloudAlbumTempIndex].artistName && iCloudAlbumArray[iCloudAlbumIndex].albumName == iCloudAlbumArrayTemp[iCloudAlbumTempIndex].albumName{
iCloudAlbumArrayTemp[iCloudAlbumTempIndex].isSelected = iCloudAlbumArray[iCloudAlbumIndex].isSelected
}
}
}
iCloudAlbumArray.removeAll()
for iCloudAlbumTempIndex in iCloudAlbumArrayTemp.indices{
iCloudAlbumArray.append(iCloudAlbumArrayTemp[iCloudAlbumTempIndex])
iCloudAlbumArray[iCloudAlbumTempIndex].urlTrackArray.sort {
return $0.trackName < $1.trackName
}
}
/* Reload table */
iCloudExportsTableView.reloadData()
}
}
}
The main problem here is that I see the file is updating in "Files" but
let isUpdating: Bool = metadataItem.value(forKey: NSMetadataUbiquitousItemIsUploadingKey) as! Bool
returns false
What am I not taking in consideration?
Thank you in advance
I have realised that despite NSMetadataUbiquitousItemIsUploadingKey returns false, NSMetadataUbiquitousItemPercentUploadedKey stills returns a number so:
let perDouble = metadataItem.value(forKey: NSMetadataUbiquitousItemPercentUploadedKey) as? Double ?? 100.00
if isUpdated{
albumICloudTrack.status = .available
}
else{
if isUpdating || perDouble < 100.00{
print("\(logClassName): isUpdating: perDouble = \(perDouble)")
albumICloudTrack.percentatge = Int(metadataItem.value(forKey: NSMetadataUbiquitousItemPercentUploadedKey) as! Double)
albumICloudTrack.status = .updating
}
Any other thoughts?

Getting a nil in Swift 3?

I am creating an app where I have annotation view showing that when you click it shows on the DetailsViewController that annotation data. However, I get "Name", and "Address" data but for phone Number I am getting set as nil. So, if you guys can see my code & help me solve it, I will be appreciated it.
Here is my code:
import UIKit
import MapKit
protocol UserLocationDelegate {
func userLocation(latitude :Double, longitude :Double)
}
class NearMeMapViewController: ARViewController, ARDataSource, MKMapViewDelegate, CLLocationManagerDelegate {
var nearMeIndexSelected = NearMeIndexTitle ()
var locationManager : CLLocationManager!
var nearMeARAnnotations = [ARAnnotation]()
var nearMeRequests = [NearMeRequest]()
var delegate : UserLocationDelegate!
var place: Place?
override func viewDidLoad() {
super.viewDidLoad()
self.title = nearMeIndexSelected.indexTitle
self.locationManager = CLLocationManager ()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.distanceFilter = kCLHeadingFilterNone
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.dataSource = self
self.headingSmoothingFactor = 0.05
self.maxVisibleAnnotations = 30
getNearMeIndexSelectedLocation()
}
func getNearMeIndexSelectedLocation()
{
let nearMeRequest = MKLocalSearchRequest()
nearMeRequest.naturalLanguageQuery = nearMeIndexSelected.indexTitle
let nearMeregion = MKCoordinateRegionMakeWithDistance(self.locationManager.location!.coordinate, 250, 250)
nearMeRequest.region = nearMeregion
let nearMeSearch = MKLocalSearch(request: nearMeRequest)
nearMeSearch.start { (response : MKLocalSearchResponse?, error :Error?) in
for requestItem in (response?.mapItems)! {
let nearMeIndexRequest = NearMeRequest ()
nearMeIndexRequest.name = requestItem.name
nearMeIndexRequest.coordinate = requestItem.placemark.coordinate
nearMeIndexRequest.address = requestItem.placemark.addressDictionary?["FormattedAddressLines"] as! [String]
nearMeIndexRequest.street = requestItem.placemark.addressDictionary?["Street"] as! String!
nearMeIndexRequest.city = requestItem.placemark.addressDictionary?["City"] as! String
nearMeIndexRequest.state = requestItem.placemark.addressDictionary?["State"] as! String
nearMeIndexRequest.zip = requestItem.placemark.addressDictionary?["ZIP"] as! String
self.nearMeRequests.append(nearMeIndexRequest)
print(requestItem.placemark.name)
}
for nearMe in self.nearMeRequests {
let annotation = NearMeAnnotation(nearMeRequest: nearMe)
self.nearMeARAnnotations.append(annotation)
self.setAnnotations(self.nearMeARAnnotations)
}
}
}
func ar(_ arViewController: ARViewController, viewForAnnotation: ARAnnotation) -> ARAnnotationView {
let annotationView = NearMeARAnnotationView(annotation: viewForAnnotation)
// annotationView.delegate = self
annotationView.frame = CGRect(x: 0, y: 0, width: 150, height: 50)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapBlurButton(_:)))
annotationView.addGestureRecognizer(tapGesture)
return annotationView
}
func tapBlurButton(_ sender: UITapGestureRecognizer) {
if let annotationView = sender.view as? NearMeARAnnotationView {
if let detailsVc = storyboard?.instantiateViewController(withIdentifier: "DetailsViewController")
as? DetailsViewController {
detailsVc.annotation = annotationView.annotation
if let annotation = annotationView.annotation as? Place {
detailsVc.place = annotation
}
self.navigationController?.pushViewController(detailsVc, animated: true)
}
}
}
}
Just looking over your code quickly:
"\(nearMeAnnotation.nearMeRequest.phone)"
All the other ones have a forced unwrap, this one doesn't. Most probably the value is nil and since you ask for a string representation of a wrapped var that might really be nil sometimes.
I think you should use a default value everywhere instead of a forced unwrap, like:
"\(nearMeAnnotation.nearMeRequest.phone ?? "")"
but also:
"\(nearMeAnnotation.nearMeRequest.street ?? "") \(nearMeAnnotation.nearMeRequest.state ?? "") \(nearMeAnnotation.nearMeRequest.state ?? "") \(nearMeAnnotation.nearMeRequest.zip ?? "")"
With forced unwraps your application will crash if a certain value is not set. This could be handled more elegantly if they're really required, for example already in the constructor of your object. There's the root cause of the optionals you're seeing. In this case NearMeAnnotation.

Crash: libsystem_pthread.dylib: _pthread_wqthread

This is the number 1 crash of my application in the AppStore. Problem is I can't find a solution to this thing, because I can't reproduce it and don't know what is causing it. The crashlog says the following:
Thread 0.8 is didUpdateLocations.
I thought it might be in checkStealRange(), but I don't see something wrong with that.
func checkStealRange() {
var objectsWithdistance = [PFObject]()
stealobject = nil
print("checkin steal and setting stealobject to nil")
if nearbystreets.count != 0 {
for object in self.nearbystreets {
if let lon = object["lon"] as? Double, let lat = object["lat"] as? Double{
let locationStreet = CLLocation(latitude: lat, longitude: lon)
if let currentLocation = self.locationManager.location {
let distance = currentLocation.distance(from: locationStreet)
object["distance"] = distance
objectsWithdistance.append(object)
} else {
if self.lastlocationregionset != nil {
let distance = self.lastlocationregionset!.distance(from: locationStreet)
object["distance"] = distance
objectsWithdistance.append(object)
}
}
}
}
} else {
print("no nearby streets loaded to check for steal")
stealButton.isEnabled = false
return
}
if objectsWithdistance.count > 0 {
print("objectsWithdistance count:", objectsWithdistance.count)
let sortedArray = (objectsWithdistance as NSArray).sortedArray(using: [
NSSortDescriptor(key: "distance", ascending: true)
])
for object in sortedArray {
guard let street = object as? PFObject else { continue }
if let streetDistance = street["distance"] as? Double {
var allowedDistance = Game.steal.stealMinDistance +
Game.steal.stealDistancePerLevel * Double(Main().level())
if Main().getStealBoost() {
allowedDistance += 250
}
//print("distance:", streetDistance, "allowed:", allowedDistance)
guard let user = street["current_owner"] as? PFUser else { continue }
if user != PFUser.current() && streetDistance <= allowedDistance {
print("found steal")
self.stealobject = street
break
}
}
}
} else {
print("checkin steal failed")
stealButton.isEnabled = false
return
}
print("nearbystreet count:", nearbystreets.count)
if !self.timecheat && stealobject != nil {
stealButton.isEnabled = true
} else {
stealButton.isEnabled = false
}
}
Re-wrote the function using Parse localdata storage, and that fixed the trick.
func checkStealRange() {
stealobject = nil
let query = PFQuery(className: "SHStreets")
if let currentLocation = self.locationManager.location {
let userGeoPoint = PFGeoPoint(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude)
query.whereKey("geo", nearGeoPoint: userGeoPoint, withinKilometers: 5)
} else {
print("no location, returning from check steal range")
self.stealButton.isEnabled = false
return
}
query.fromLocalDatastore()
query.findObjectsInBackground { (objects : [PFObject]?, error: Error?) in
if error != nil {
print(error as Any)
self.stealButton.isEnabled = false
return
}
if objects == nil || objects!.count == 0 {
print("no nearby streets loaded to check for steal")
self.stealButton.isEnabled = false
return
}
if objects != nil {
for (index, object) in objects!.enumerated() {
guard let lon = object["lon"] as? Double else { continue }
guard let lat = object["lat"] as? Double else { continue }
let locationStreet = CLLocation(latitude: lat, longitude: lon)
if let currentLocation = self.locationManager.location {
let distance = currentLocation.distance(from: locationStreet)
//steal distance
var allowedDistance = Game.steal.stealMinDistance + Game.steal.stealDistancePerLevel * Double(Main().level())
if Main().getStealBoost() {
allowedDistance += 250
}
print("distance for street:" , index + 1, "is", distance, "allowed:", allowedDistance)
guard let user = object["current_owner"] as? PFUser else { continue }
if user != PFUser.current() && distance <= allowedDistance {
print("found steal")
self.stealobject = object
if !self.timecheat && self.stealobject != nil && !self.stealinprogress {
self.stealButton.isEnabled = true
} else {
self.stealButton.isEnabled = false
}
return
}
}
}
}
}
}

Resources