Something like this I want to add current timestamp when recording is done in the video and save into camera roll.
**Note **: I have successfully added current location and timestamp in AVVideoPreviewLayer but it is static after exporting video is show static time does not show running timestamp
Try creating a layer of previewLayer: UIView with the components you want to have on camera.
Add this layer to currently running session of AVCaptureVideoPreviewLayer.
This link might help you to achieve your problem
Adding objects over camera view in app (Swift 3) not under camera view?
I tried something out. I guess you want to get latitude, longitude and the timestamp.
You find an example for latitude and longitude below.
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func showLocation(_ sender: Any) {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if(CLLocationManager.locationServicesEnabled()){
locationManager.startUpdatingLocation()
}
locationManager.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0] as CLLocation
print("user latitude = \(userLocation.coordinate.latitude)")
print("user longitude = \(userLocation.coordinate.longitude)")
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{
print("Error \(error)")
}
}
To get the current time you can use something like this:
let date = NSDate()
print(date)
The result for both in console should look something like this:
2017-12-17 21:45:39 +0000
user latitude = 37.3322499
user longitude = -122.056264
(The time looks like this in my example because im from EU but you can convert it to what you want)
You can add this to a separate view and bring it to front with
view.bringSubview(toFront: YourView)
I hope this is helpful!
Related
I am new to swift and am trying to get a basic program that display the longitude and latitutde.
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var latLabel: UILabel!
#IBOutlet weak var longLabel: UILabel!
#IBOutlet weak var addLabel: UILabel!
var lm = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
lm = CLLocationManager()
}
#IBAction func getCurrentLocation(_ sender: AnyObject) {
lm.delegate = self
lm.desiredAccuracy = kCLLocationAccuracyBest
lm.startUpdatingLocation()
print("loc")
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print ("error")
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print ("location")
let length = locations.count
let curLoc = locations[length-0]
latLabel.text = String(curLoc.coordinate.latitude)
print ("loccation")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You are missing two things.
you have to ask for permission using requestAlwaysAuthorization or requestWhenInUseAuthorization().
So when you are allocating your location manager in viewdidlod, Do like this
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
You need to add information as #Anbu.Karthik has suggested in his answer.
Use NSLocationAlwaysUsageDescription for apps that want to use the
device's location even when the app is not open and being used.
Use NSLocationWhenInUseUsageDescription for apps that want to use the
device's location only when the app is open and in use.
check once are you added the following information your plist
Location :
Key : Privacy - Location Always Usage Description
Value : $(PRODUCT_NAME) location use
Key : Privacy - Location When In Use Usage Description
Value : $(PRODUCT_NAME) location use
for more information see this
One other issue that I found caused the location update callback not to be called, with no obvious error message given is that it must not be a private function (which is obvious once you finally notice it, of course...). I realise the OP's one is not but this is a common place to end up if you are having issues, so it may help someone.
So the following will cause the function not to be called without giving any obvious error indication like crashing the app etc:
private func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print ("location")
let length = locations.count
let curLoc = locations[length-0]
latLabel.text = String(curLoc.coordinate.latitude)
print ("loccation")
}
Removing the 'private' keyword, as in the OP's code, will allow it to be called.
I'm learning about user localization in swift. I'm trying to print localization on console (later I will use it for info on label, so I want to check if it works), but I have no idea why it prints nothing. Even if delete conversions to string, and leave just for printing anything, it still doesn't work. Please help.
Yes, I added NSLocationAlwaysUsageDescription and
NSLocationWhenInUseUsageDescription.
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
var myPosition = CLLocationCoordinate2D()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
print("Got location: \(newLocation.coordinate.latitude), \(newLocation.coordinate.longitude)")
myPosition = newLocation.coordinate
locationManager.stopUpdatingLocation()
}
}
didUpdateToLocation is an outdated method of the CLLocationManagerDelegate. It is available in 10.6 and earlier. Instead, use didUpdateLocations, which will return an array of all location objects in order of time recent. You then access the latest, newest location be grabbing the last object in the returned array.
So try this
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
var latestLocation: CLLocation = locations.last;
print("Got location: \(latestLocation.coordinate.latitude), \(latestLocation.coordinate.longitude)")
}
tell me how it goes.
info.plist file:
<key>NSLocationWhenInUseUsageDescription</key>
<string>This project would like to know your location</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>location when app is in background</string>
As shown above, have added the key/value pairs for the info.plist
The problem i'm facing is that the first time i ran the app it prompted me for authorization, but, on subsequent runs the popup hasn't appeared.
second, I'm trying to print the locations from
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) using the print(location) but nothing is printed.
in the debug options i have set location as "city bicycle ride"
The code i'm using is as follows.
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate , CLLocationManagerDelegate {
#IBOutlet var map: MKMapView!
//use the locManager to get the users location
var locManager = CLLocationManager()
override func viewDidLoad() {
locManager.delegate = self
locManager.desiredAccuracy = kCLLocationAccuracyBest
locManager.requestWhenInUseAuthorization()
super.viewDidLoad()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
iOS will ask only once for location authorization. If the user denies, he will have to change this in the device settings manually. If he agrees, you will be able to obtain the location until he blocks it in the device settings.
So this code:
locManager.requestWhenInUseAuthorization()
will prompt a popup only 1 time. The problem is that you probably forget to call:
locManager.startUpdatingLocation()
You need to call this every time you want to start obtaining the location.
use this
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestLocation()
locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
I am trying to calculate the distance from the starting position I am (when i first start the app) to the current position and present it on a label (meters.text) but nothing appears on it..
Here is my code:
import UIKit
import CoreLocation
class CorrectViewController: UIViewController,CLLocationManagerDelegate {
#IBOutlet weak var meters: UILabel!
var wr: Int = 0
var distance = CLLocationDistance()
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization() //starts when i use the app
self.locationManager.distanceFilter = kCLHeadingFilterNone
self.locationManager.startUpdatingLocation()
}
//locatioManager delegate method
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
let currentLocation: CLLocation = newLocation
let startLocation: CLLocation = oldLocation
distance = startLocation.distanceFromLocation(currentLocation)
let tripString = NSString(format: "%.2f", distance)
meters.text = ("\(tripString)")
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
meters.text = ("error!")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
Any help is appreciated:)
It appears that the location update delegate method is inside the viewDidLoad function and hence defines a local function rather than implementing the delegate method.
Move the following method out of the viewDidLoad scope:
locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation)
In addition you are not requesting permission to use the users location. Make sure to do that and add the necessary string to your info plist.
Also: oldLocation will always be the previous location (not your initial one).
Alright, after a lot of searching and "trial and error" I found the solution here.
Instead of using the method didUpdateToLocation the method didUpdateLocations should be used. Moreover, it is really important to put NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription keys in the .plist file (value may be an additional message that will be presented in location alert). These keys are required in iOS 8.
The below code is getting the user current location and creating a mapbox map.
problem is that the mapbox map is being created before the users location is obtain.
How may I slow or sync this process?
Thank you in advance,
import UIKit
import CoreLocation
import MapboxGL
class AViewController: UIViewController, CLLocationManagerDelegate {
var manager:CLLocationManager!
var userLocation:CLLocation = CLLocation(latitude: 25.776243, longitude: -80.136509)
override func viewDidLoad() {
super.viewDidLoad()
println("inside viewdidload")
self.getUserLocation()
}//eom
override func viewDidAppear(animated: Bool) {
println("inside viewdidappear")
self.createMapBoxMap()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*** MapBox Functions ************************************************************************/
/*Create preliminary map */
func createMapBoxMap(){
// set your access token
let mapView = MGLMapView(frame: view.bounds, accessToken: "pk.eyJ1IjoiZGFya2ZhZGVyIiwiYSI6IlplVDhfR3MifQ.pPEz732qS8g0WEScdItakg")
mapView.autoresizingMask = .FlexibleWidth | .FlexibleHeight
// set the map's center coordinate
mapView.setCenterCoordinate(CLLocationCoordinate2D(latitude: self.userLocation.coordinate.latitude, longitude: self.userLocation.coordinate.longitude),
zoomLevel: 13, animated: false)
view.addSubview(mapView)
//showing the user location on map - blue dot
mapView.showsUserLocation = true
}//eom
/*** location Functions ************************************************************************/
/*getting user current location*/
func getUserLocation(){
self.manager = CLLocationManager()
self.manager.delegate = self
self.manager.desiredAccuracy = kCLLocationAccuracyBest
self.manager.requestWhenInUseAuthorization()
self.manager.startUpdatingLocation()
}//eom
/*location manager 'didUpdateLocations' function */
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
self.manager.stopUpdatingLocation() //stop getting user location
println(locations)
self.userLocation = locations[0] as! CLLocation
}//eom
/* errors occurred */
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError) {
println("Error:" + error.localizedDescription)
}//eom
}//eoc
Location manager is running asynchronously (expected behavior), which means that it returns immediately and finishes creating the map as soon as the create map box method is called. However, it doesn't mean that the map has gotten a location yet. I'm thinking that the best way to implement this would be to move self.createMapBoxMap() to inside didUpdateLocations and try that. From my experience, you want the creation of your view to happen in a callback from an asynchronous method like this. You might want to have some type of loading view though, because the user will be confused at first.