Thread 0 crashed with ARM Thread State (64-bit) - ios

I submited my app to app store, they said its crash when app launch. But for my device adn in simulator its working fine. Not able to find whats the issues here.
I attached the binary image with crash file what apple gave me.please let me know any 1 able to get the issue.
Here is that crash file
Thanks
the crash showed here :
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 WCi 0x0000000100df0454 specialized closure #1 in MainScreenViewController.getAdressName(coords:) + 509012 (MainScreenViewController.swift:668)
1 WCi 0x0000000100e01ed4 partial apply for closure #1 in MainScreenViewController.getAdressName(coords:) + 581332 (MainScreenViewController.swift:0)
2 WCi 0x0000000100de0288 _T0SaySo11CLPlacemarkCGSgs5Error_pSgIegxx_So7NSArrayCSgSo7NSErrorCSgIeyByy_TR + 443016 (MainScreenViewController.swift:0)
3 libdispatch.dylib 0x00000001d96596c8 0x1d95f9000 + 394952
4 libdispatch.dylib 0x00000001d965a484 0x1d95f9000 + 398468
5 libdispatch.dylib 0x00000001d96069a4 0x1d95f9000 + 55716
6 CoreFoundation 0x00000001d9bb0df4 0x1d9b05000 + 703988
7 CoreFoundation 0x00000001d9babcbc 0x1d9b05000 + 683196
8 CoreFoundation 0x00000001d9bab1f0 0x1d9b05000 + 680432
9 GraphicsServices 0x00000001dbe24584 0x1dbe19000 + 46468
10 UIKitCore 0x0000000206b38c00 0x206250000 + 9341952
11 WCi 0x0000000100dbeba4 main + 306084 (AppDelegate.swift:23)
12 libdyld.dylib 0x00000001d966abb4 0x1d966a000 + 2996
so in my MainScreenViewController.swift
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if firstload == false {
firstload = true
firstTimeLoads = true
currentlocation = locations.last!
let cityCoords = CLLocation(latitude: currentlocation.coordinate.latitude, longitude: currentlocation.coordinate.longitude)
let addresss = getAdressName(coords: cityCoords)
self.userlat = "\(currentlocation.coordinate.latitude)"
self.userlong = "\(currentlocation.coordinate.longitude)"
self.userDevice = "iOS"
self.userName = Uname ?? "NA"
self.userId = UId ?? "NA"
self.userTime = time
let camera = GMSCameraPosition.init(target: currentlocation.coordinate, zoom: 11, bearing: 0, viewingAngle: 0)
passloc = String(format: "%f,%f", currentlocation.coordinate.latitude,currentlocation.coordinate.longitude)
if let locationData = passloc {
self.movelocation = currentlocation
UserDefaults.standard.set(locationData, forKey: "storemyloc")
UserDefaults.standard.synchronize()
viewmap.animate(to: camera)
self.getAddressFromLatLon(location: currentlocation)
print("my address")
print(currentlocation)
print("LOG: LOCATION 1 \(searchlocation)")
if CLLocationCoordinate2DIsValid(self.searchlocation.coordinate) {
self.movelocation = self.searchlocation
} else {
self.runlink()
}
}
}
}
func getAdressName(coords: CLLocation) {
CLGeocoder().reverseGeocodeLocation(coords) { (placemark, error) in
if error != nil {
print("Hay un error")
} else {
let place = placemark! as [CLPlacemark]
if place.count > 0 {
let place = placemark![0]
var adressString : String = ""
if place.locality != nil {
adressString = adressString + place.name! + " - "
}
if place.thoroughfare != nil {
adressString = adressString + place.subLocality! + ", "
}
if place.locality != nil {
adressString = adressString + place.subAdministrativeArea! + " - "
}
if place.country != nil {
adressString = adressString + place.country!
}
self.Userdic.setValue(adressString, forKey: "useraddress")
self.userAdd = adressString
}
}
}
}
whats might be the issues here for that crash ? Cordinates - lat,long is not passed or issues is with func getAdressName(coords: CLLocation)

Replace your getAdressName with below code.
func getAdressName(coords: CLLocation) {
CLGeocoder().reverseGeocodeLocation(coords) { (placemark, error) in
if error != nil {
print("Hay un error")
} else {
let place = placemark! as [CLPlacemark]
if place.count > 0 {
let place = placemark![0]
var adressString : String = ""
if place.name != nil {
adressString = adressString + place.name! + " - "
}
if place.subLocality != nil {
adressString = adressString + place.subLocality! + ", "
}
if place.subAdministrativeArea != nil {
adressString = adressString + place.subAdministrativeArea! + " - "
}
if place.country != nil {
adressString = adressString + place.country!
}
self.Userdic.setValue(adressString, forKey: "useraddress")
self.userAdd = adressString
}
}
}
}
You checking the nil of locality but inside getting the value of place.subAdministrativeArea! which might in nil case.

Related

CLGeocoding, facing problem when reverse geocode and getting the address from LAT LONG to show in tableView [duplicate]

This question already has answers here:
How do i return coordinates after forward geocoding?
(3 answers)
block until reverseGeocode has returned
(1 answer)
Closed 3 years ago.
I am new swift. I have a task that need to complete. I am getting response from server, where I get numbers of Latitude and Longitude.
{
EndLat = "28.511593";
EndtLong = "77.071136";
},
{
EndLat = "28.511593";
EndtLong = "77.071136";
},.....
getting this type of response having more than 100s of entry.
Now when I'm fetching the address through reverse geocoding..
func getAddressForLogOut(pdblLatitude: String, withLongitude pdblLongitude: String) {
if (pdblLatitude != "") && (pdblLongitude != "") {
var center : CLLocationCoordinate2D = CLLocationCoordinate2D()
let lat: Double = Double("\(pdblLatitude)")!
//21.228124
let lon: Double = Double("\(pdblLongitude)")!
//72.833770
let ceo: CLGeocoder = CLGeocoder()
center.latitude = lat
center.longitude = lon
let loc: CLLocation = CLLocation(latitude:center.latitude, longitude: center.longitude)
ceo.reverseGeocodeLocation(loc, completionHandler:
{(placemarks, error) in
if (error != nil)
{
print("reverse geodcode fail: \(error!.localizedDescription)")
}
let pm = placemarks! as [CLPlacemark]
if pm.count > 0 {
let pm = placemarks![0]
print(pm.country)
print(pm.locality)
print(pm.subLocality)
print(pm.thoroughfare)
print(pm.postalCode)
print(pm.subThoroughfare)
var addressString : String = ""
if pm.subLocality != nil {
addressString = addressString + pm.subLocality! + ", "
}
if pm.thoroughfare != nil {
addressString = addressString + pm.thoroughfare! + ", "
}
if pm.locality != nil {
addressString = addressString + pm.locality! + ", "
}
if pm.country != nil {
addressString = addressString + pm.country! + ", "
}
if pm.postalCode != nil {
addressString = addressString + pm.postalCode! + " "
}
print(addressString)
self.endAdd = addressString
print("self.endAdd is",self.endAdd)
}
} )
}
}
I'm using that function in tableView's cellForRowAtIndexPath functon. when i scroll the table view the app get crash. getting nil at placemark!
let pm = placemarks! as [CLPlacemark] at this line.
Can any help me to use the reverse geocoding that let me fetching the address of more than 100s of latitude and longitude and show it up in tableView.
CLGeocoder returns an optional type:
typealias CLGeocodeCompletionHandler = ([CLPlacemark]?, Error?) -> Void
(from doc)
you should check it.
I think that usage a cell for data loading from geocoder is bad idea, because you will have a race:
start request1(lat1,lon1)
reusing cell
start request2(lat2,lon2)
response from geocoder for request1
At 4) a cell shows inconsistent data.

Crashed: com.apple.main-thread EXC_BREAKPOINT 0x0000000100c5009c keyboard_arrow_up

I am new iOS development, I got this error from firebase crash analytics. Can anyone help me why this errors occurs?
Crashed: com.apple.main-thread
0 People Time Tracking 0x100c5009c closure #1 in closure #1 in SelectJobScreen.getPreviousStatus() (SelectJobScreen.swift:798)
1 People Time Tracking 0x100cb2648 thunk for #escaping #callee_guaranteed () -> () (<compiler-generated>)
2 libdispatch.dylib 0x1e6993a38 _dispatch_call_block_and_release + 24
3 libdispatch.dylib 0x1e69947d4 _dispatch_client_callout + 16
4 libdispatch.dylib 0x1e6942004 _dispatch_main_queue_callback_4CF$VARIANT$mp + 1068
5 CoreFoundation 0x1e6ee4ec0 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 12
6 CoreFoundation 0x1e6edfdf8 __CFRunLoopRun + 1924
7 CoreFoundation 0x1e6edf354 CFRunLoopRunSpecific + 436
8 GraphicsServices 0x1e90df79c GSEventRunModal + 104
9 UIKitCore 0x212cc5b68 UIApplicationMain + 212
10 People Time Tracking 0x100c1afcc main (TodoItem.swift:17)
11 libdyld.dylib 0x1e69a58e0 start + 4
I've tried figuring out what could cause this crash for a few days now, and haven't been able to reproduce it. I don't see any implicit unwraps or optionals here, but sessionId is a non-optional value in the session object if that matters.
I am using swift 4.1, and the crashes occur on on iOS devices running all the different flavours of iOS 10, 11, and 12. The app does support some builds of iOS 9, but none have been reported (although that may be irrelevant because the iOS 9 user base for the app is extremely small)
In Error log it's showing this function getPreviousStatus()
func getPreviousStatus() {
let connect = JsonManger()
let app = UIApplication.shared.delegate as! AppDelegate
let user:User = app.dataManager.gUser
if Reachability.isConnectedToNetwork() {
self.showHUD( msg: "Loading...." )
connect.getLogDetails(baseUrl: user.ClientWeb, email: user.EmailID, password: user.Password, brugerId: user.BrugerID, success: { (res) in
var indud = false
if ( res.object(forKey: "indud") != nil ){
indud = res.object(forKey: "indud") as! Bool
}
if indud {
var isTodo = false
if res.object(forKey: "isToDo") != nil {
isTodo = res.object(forKey: "isToDo") as! Bool
}
if isTodo {
var str = res.object(forKey: "JobId") as! String
let index = str.index(str.startIndex, offsetBy: 1)
str = str.substring(from: index)
let prjId = Int(str)!
let project = app.dataManager.gProject.getProject(id: prjId)
let todoId = res.object(forKey: "TodoId") as! String
let todo = app.dataManager.gTodo.getTodo(id: Int(todoId)!)
self.project = project
self.todoItem = todo
app.dataManager.isCheckedin = true
self.des = res.object(forKey: "JobDescription") as? String
let startTime = res.object(forKey: "Dato2") as! String
DispatchQueue.main.async {
let ud = UserDefaults.standard
ud.set(true, forKey: "isCheckedIn")
ud.set( 1, forKey:"type")
ud.set( self.project.ID!, forKey: "projectId" )
ud.set( self.todoItem.ID! , forKey: "todoId" )
// print(" todo data is : \(self.todoItem.ID!)")
ud.set( self.des, forKey: "des")
ud.set( startTime,forKey: "startTime")
ud.set( startTime, forKey: "checkInTime" )
ud.synchronize()
self.hideHUD()
self.performSegue(withIdentifier: "goStartTodoFromSelect", sender: nil )
}
} else {
var jobId = res.object(forKey: "JobId") as! String
jobId = jobId.replacingOccurrences(of: "P", with: "")
self.des = res.object(forKey: "JobDescription") as? String
let jobCode = app.dataManager.gJobCode.getJobCode(id: Int(jobId)! )
self.jobCodeItem = jobCode
// let chekinTime = res.object(forKey: "Dato2") as! String
let startTime = "2019-05-15T19:45:00"
DispatchQueue.main.async {
app.dataManager.isCheckedin = true
let ud = UserDefaults.standard
ud.set(true, forKey: "isCheckedIn")
ud.set( 0, forKey:"type")
ud.set( jobId, forKey: "jobId" )
ud.set( startTime,forKey: "startTime")
ud.set( startTime, forKey: "checkInTime" )
if res.object(forKey: "JobDescription") != nil {
self.des = res.object(forKey: "JobDescription") as? String
ud.set( self.des, forKey: "des")
}
ud.synchronize()
DispatchQueue.main.async {
self.hideHUD()
self.performSegue(withIdentifier: "goStartJob", sender: nil )
}
}
}
} else {
DispatchQueue.main.async {
self.hideHUD()
// self.popToRoot()
for controller in self.navigationController!.viewControllers as Array {
if controller.isKind(of: SelectJobScreen.self) {
self.navigationController!.popToViewController(controller, animated: true)
break
}
}
}
}
}) { (error) in
DispatchQueue.main.async {
self.hideHUD()
// self.popToRoot()
for controller in self.navigationController!.viewControllers as Array {
if controller.isKind(of: SelectJobScreen.self) {
self.navigationController!.popToViewController(controller, animated: true)
break
}
}
}
}
} else {
print("Record Not Found")
}
}
Inside of that getPreviousStatus() functions getting null values , check it once using debugging
DispatchQueue.main.async {
# mainly in this thread getting error check it once
let ud = UserDefaults.standard
ud.set(true, forKey: "isCheckedIn")
ud.set( 1, forKey:"type")
ud.set( self.project.ID!, forKey: "projectId" )
ud.set( self.todoItem.ID! , forKey: "todoId" )
// print(" todo data is : \(self.todoItem.ID!)")
ud.set( self.des, forKey: "des")
ud.set( startTime,forKey: "startTime")
ud.set( startTime, forKey: "checkInTime" )
ud.synchronize()
self.hideHUD()
self.performSegue(withIdentifier: "goStartTodoFromSelect", sender: nil )
}

Google map Place information by latitude and longitude in iOS Swift

I have a marker on map. When scroll map, then the marker also moves. I can find the marker coordinates, but how to find place information using that coordinate?
Place information of current location
func locate() {
placesClient.currentPlace(callback: { (placeLikelihoodList, error) -> Void in
if let error = error {
print("Pick Place error: \(error.localizedDescription)")
return
}
let placeInfo = getCurrentPlaceInformation()
self.placeNameLbl.text = placeInfo.name
self.placeAddressLbl.text = placeInfo.address
if let placeLikelihoodList = placeLikelihoodList {
let place = placeLikelihoodList.likelihoods.first?.place
if let place = place {
print("LOG: place name : \(place.name), place Address : \(place.formattedAddress)")
PLACE_NAME = place.name
PLACE_ADDRESS = place.formattedAddress ?? ""
let placeInfo = getCurrentPlaceInformation()
self.placeNameLbl.text = placeInfo.name
self.placeAddressLbl.text = placeInfo.address
}
}
})
}
How to find custom coordinates to find place information?
Apple reverse Geocode API
import CoreLocation
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(<#T##location: CLLocation##CLLocation#>, completionHandler: <#T##CLGeocodeCompletionHandler##CLGeocodeCompletionHandler##([CLPlacemark]?, Error?) -> Void#>)
Google reverse Geocode API
Add GoogleMaps to project (can use pods)
let geocoder = GMSGeocoder()
geocoder.reverseGeocodeCoordinate(position) { response, error in
//
if error != nil {
print("reverse geodcode fail: \(error!.localizedDescription)")
} else {
if let places = response?.results() {
if let place = places.first {
if let lines = place.lines {
print("GEOCODE: Formatted Address: \(lines)")
}
} else {
print("GEOCODE: nil first in places")
}
} else {
print("GEOCODE: nil in places")
}
}
}
func getAddrFrmLtLng(latitude:Any, longitude:Any){
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: latitude as! CLLocationDegrees, longitude: longitude as! CLLocationDegrees)
geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
var placeMark: CLPlacemark!
placeMark = placemarks?[0]
self.displayLocationInfo(placemark: placeMark)
})
}
func displayLocationInfo(placemark: CLPlacemark?) -> String {
var locality = ""
var postalCode = ""
var administrativeArea = ""
var country = ""
var sublocality = ""
var throughfare = ""
var name = ""
if let containsPlacemark = placemark {
//stop updating location to save battery life
// locationManager.stopUpdatingLocation()
locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality! : ""
postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode! : ""
administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea! : ""
country = (containsPlacemark.country != nil) ? containsPlacemark.country! : ""
sublocality = (containsPlacemark.subLocality != nil) ? containsPlacemark.subLocality! : ""
throughfare = (containsPlacemark.thoroughfare != nil) ? containsPlacemark.thoroughfare! : ""
}
var adr: String = ""
if throughfare != "" {
adr = throughfare + ", "
}
if sublocality != "" {
adr = adr + sublocality + ", "
}
if locality != "" {
adr = adr + locality + ", "
}
if administrativeArea != "" {
adr = adr + administrativeArea + ", "
}
if postalCode != "" {
adr = adr + postalCode + ", "
}
if country != "" {
adr = adr + country
}
print(adr)
return adr
}

How to get the address from the coordinate

I want to get the address from the coordinate. I have attached my code below..
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let lastLocation = locations.last!
let latvalue = lastLocation.coordinate.latitude
let lngvalue = lastLocation.coordinate.longitude
self.db_latvalue = latvalue
self.db_lngvalue = lngvalue
let location = CLLocation(latitude: latvalue, longitude:lngvalue)
let address = CLGeocoder.init()
address.reverseGeocodeLocation(CLLocation.init(latitude: latvalue, longitude:lngvalue)) { (places, error) in
if error == nil{
if let place = places{
print("addressshowingssq \(place)")
self.db_address = "\(place)"
}
}
}
Output:
[L-30 2nd A Main Road, L-30 2nd A Main Road, HSR Layout, Bengaluru,
Karnataka 560102, India # <+12.91597974,+77.62879254> +/- 100.00m,
region CLCircularRegion (identifier:'<+12.91597974,+77.62879254>
radius 70.94', center:<+12.91597974,+77.62879254>, radius:70.94m)]
I want only the address as i mention below
L-30 2nd A Main Road, L-30 2nd A Main Road, HSR Layout, Bengaluru,
Karnataka 560102
I researched google i got different solution so i got confused.
Update
I have done a few modification to iVarun's solution. This is simpler. and working.
First, add this function:
func geocode(latitude: Double, longitude: Double, completion: #escaping (CLPlacemark?, Error?) -> ()) {
CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: latitude, longitude: longitude)) { completion($0?.first, $1) }
}
After that,
get the address:
geocode(latitude: latvalue, longitude: lngvalue) { placemark, error in
guard let placemark = placemark, error == nil else { return }
// you should always update your UI in the main thread
DispatchQueue.main.async {
// update UI here
print("address1:", placemark.thoroughfare ?? "")
print("address2:", placemark.subThoroughfare ?? "")
print("city:", placemark.locality ?? "")
print("state:", placemark.administrativeArea ?? "")
print("zip code:", placemark.postalCode ?? "")
print("country:", placemark.country ?? "")
}
}
Result:
address1: Rua Casuarina
address2: 443
city: Rio de Janeiro
state: RJ
zip code: 20975
country: Brazil
As #iOSer indicated, CLPlacemark is capable of giving you this part of the string, However.
You could split the string:
let output:String = "[L-30 2nd A Main Road, L-30 2nd A Main Road, HSR Layout, Bengaluru, Karnataka 560102, India # <+12.91597974,+77.62879254> +/- 100.00m, region CLCircularRegion (identifier:'<+12.91597974,+77.62879254> radius 70.94', center:<+12.91597974,+77.62879254>, radius:70.94m)]"
let items = output.components(separatedBy: "#")
print(items[0])
Becuse the # will be always included, you could skip the rest.
Result:
Hope this will help you:
address.reverseGeocodeLocation(CLLocation.init(latitude: latvalue, longitude:lngvalue)) { (places, error) in
if error == nil{
let placeMark = places! as [CLPlacemark]
if placeMark.count > 0 {
let placeMark = places![0]
var addressString : String = ""
if placeMark.subThoroughfare != nil {
addressString = addressString + placeMark.subThoroughfare! + ", "
}
if placeMark.thoroughfare != nil {
addressString = addressString + placeMark.thoroughfare! + ", "
}
if placeMark.subLocality != nil {
addressString = addressString + placeMark.subLocality! + ", "
}
if placeMark.locality != nil {
addressString = addressString + placeMark.locality! + ", "
}
if placeMark.administrativeArea != nil {
addressString = addressString + placeMark.administrativeArea! + ", "
}
if placeMark.country != nil {
addressString = addressString + placeMark.country! + ", "
}
if placeMark.postalCode != nil {
addressString = addressString + placeMark.postalCode! + " "
}
print(addressString)
}
}
}
Output:
L-30, 2nd A Main Road, HSR Layout, Bengaluru, Karnataka, India, 560102
Swift 3
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
let objLocation = CLLocation(latitude: locValue.latitude, longitude: locValue.longitude)
CLGeocoder().reverseGeocodeLocation(objLocation) { (placemarksArray, error) in
if error != nil {
print("Reverse geocoder failed with error" + (error?.localizedDescription)!)
return
}
if (placemarksArray?.count)! > 0 {
let objPlacemark = placemarksArray?[0]
self.generateAddress(objPlacemark: objPlacemark!)
self.locationManager?.stopUpdatingLocation()
self.locationManager = nil
}
else {
print("Problem with the data received from geocoder")
}
}
}
Function Parsing placemark to string...
func generateAddress(objPlacemark : CLPlacemark) -> String {
print("objPlacemark : \(objPlacemark.description)")
var completeAddress = ""
if objPlacemark.name != nil {
completeAddress = String(describing: objPlacemark.name!)
}
if objPlacemark.thoroughfare != nil && (objPlacemark.name != objPlacemark.thoroughfare) {
completeAddress = completeAddress + ", " + String(describing: objPlacemark.thoroughfare!)
}
if objPlacemark.subThoroughfare != nil {
completeAddress = completeAddress + ", " + String(describing: objPlacemark.subThoroughfare!)
}
if objPlacemark.subLocality != nil {
completeAddress = completeAddress + "," + String(describing: objPlacemark.subLocality!)
}
if objPlacemark.locality != nil {
completeAddress = String(describing: objPlacemark.locality!)
}
if objPlacemark.postalCode != nil {
completeAddress = completeAddress + "," + String(describing: objPlacemark.postalCode!)
}
if objPlacemark.administrativeArea != nil {
completeAddress = completeAddress + "," + String(describing: objPlacemark.administrativeArea!)
}
if objPlacemark.isoCountryCode != nil {
completeAddress = completeAddress + "," + String(describing: objPlacemark.isoCountryCode!)
}
print("completeAddress : \(completeAddress)")
return completeAddress
}
CLGeocodeCompletionHandler contains an array of CLPlacemark. You can access its properties such as name, locality, isoCountryCode etc to form a complete address!!

On Load Server Posting Occurring Before Location Services Locates User

Does location services run in the background? I noticed that when I read the location from location manager into a global variable a post to parse-server it doesn't reflect the location data after insert. I suspect that this is because the post code is running before the location manager function sets variables because it runs in the background.
Is there a way to start a location manager in view did load, but make sure that View did load waits until location services has finished its first update?
// VIEW DID LOAD
override func viewDidLoad() {
super.viewDidLoad()
self.imagePicker.delegate = self
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
var secondsFromGMT: Int { return TimeZone.current.secondsFromGMT()
// -----------------------
// ? Wait for LOCATION SERVICES?? if placeIsSet {}
// -----------------------
let post = PFObject(className: "BlipPost")
// need struct2Parse() function
post["user_id"] = curBlip.user_id
post["blip_msg"] = curBlip.blip_note
post["blip_date"] = curBlip.blip_dt
post["TZOffset_seconds"] = curBlip.blip_tz_secs
post["blip_address"] = curBlip.blip_addr
post["latitude"] = curBlip.blip_lat
post["longitude"] = curBlip.blip_lon
post["IsPublic"] = curBlip.isPublic
print("location set about to post= \(locationSet)")
post.saveInBackground { (success, error) in
if success {
print("location set success= \(self.locationSet)")
print("Blip instantiated")
curBlip.blip_id = post.objectId!
// Should we add the new blip now or wait on "Save"
} else {
print("\(error?.localizedDescription ?? "")")
}
}
// LOCATION MANAGER
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let addrDelim = " "
let userLocation: CLLocation = locations[0]
currLocation = userLocation
let latitude = userLocation.coordinate.latitude
let longitude = userLocation.coordinate.longitude
location.lat = latitude
location.lon = longitude
location.strLatitude = String(format: "%.8f", latitude)
location.strLongitude = String(format: "%.8f", longitude)
location.strCourse = String(userLocation.course)
location.strSpeed = String(userLocation.speed)
location.strAltitude = String(userLocation.altitude)
location.strLatLon = location.strLatitude + ", " + location.strLongitude
locationSet = true
// Reverse Geo Code for addr
CLGeocoder().reverseGeocodeLocation(userLocation) { (placemarks, error) in
if error != nil {
print(error!)
} else {
if let placemark = placemarks?[0] {
var address = ""
if placemark.subThoroughfare != nil {
address += placemark.subThoroughfare! + " "
self.location.subThoroughfare = placemark.subThoroughfare!
}
if placemark.thoroughfare != nil {
address += placemark.thoroughfare! + addrDelim
self.location.thoroughfare = placemark.thoroughfare!
}
if placemark.subLocality != nil {
address += placemark.subLocality! + addrDelim
self.location.subLocality = placemark.subLocality!
}
if placemark.subAdministrativeArea != nil {
address += placemark.subAdministrativeArea! + addrDelim
self.location.subAdministrativeArea = placemark.subAdministrativeArea!
}
if placemark.postalCode != nil {
address += placemark.postalCode! + addrDelim
self.location.postalCode = placemark.postalCode!
}
if placemark.country != nil {
address += placemark.country! + addrDelim
self.location.country = placemark.country!
}
self.location.strAddress = address
print("location set in Manager= \(self.locationSet)")
print(self.location.strAddress)
}
}
}
// Stop updating location to save battery
locationManager.stopUpdatingLocation()
}

Resources