Get current location from osx/cocoa app using xcode swift 3 - xcode

I apologize for not providing it with a code. The reason I posted it with images because xcode is LLVM(low level virtual machine) compiler which has mostly UI environment especially for the configuration part. Such as creating either an outlet or action for object by dragging them to the view controller instead defining it by a code directly. Thus since it was so, I think people would easily notice my mistake faster.
import Cocoa
import MapKit
class ViewController: NSViewController, CLLocationManagerDelegate {
#IBOutlet var mapView: MKMapView!
var locManager = CLLocationManager()
var currentLocation = CLLocation()
var locationManager = CLLocationManager()
var didFindMyLocation = false
var strForCurLatitude = "";
var strForCurLongitude = "";
override func viewDidLoad() {
super.viewDidLoad()
let distancespan:CLLocationDegrees = 2000
let busCScampuslocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(currentLocation.coordinate.latitude, currentLocation.coordinate.longitude)
mapView.setRegion(MKCoordinateRegion.init(center: bsuCScampuslocation, latitudinalMeters: distancespan, longitudinalMeters: distancespan), animated: true)
print(currentLocation.coordinate.latitude)
}
...
}

Swift 5:
ViewController.swift
import Cocoa
import CoreLocation
import MapKit
class ViewController: NSViewController, CLLocationManagerDelegate {
let manager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
manager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations)
//This is where you can update the MapView when the computer is moved (locations.last!.coordinate)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
func locationManager(_ manager: CLLocationManager,
didChangeAuthorization status: CLAuthorizationStatus) {
print("location manager auth status changed to: " )
switch status {
case .restricted:
print("restricted")
case .denied:
print("denied")
case .authorized:
print("authorized")
case .notDetermined:
print("not yet determined")
default:
print("Unknown")
}
}
Add these lines to Info.plist or set the NSLocationAlwaysAndWhenInUseUsageDescription and/(or?) NSLocationUsageDescription to a plaintext description of why you need to access the users location
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Allows us to locate you</string>
<key>NSLocationUsageDescription</key>
<string>Allows us to locate you</string>
If the user has Location Services off, the authorization status will be 'denied'

Related

How do I make Location permission request trigger only when the user clicks on the map tab in a UITabBar?

I am building an app using UITabBar and one of the tab items is a map. I only want the user to have to respond to the LocationService() request when they tap on the map tab. However, when the app loads to the tabBar, the location permission request pops up first thing.
Here is the code for the LocationService()
import CoreLocation
protocol LocationServiceDelegate: class {
func authorizationDenied()
func setMapRegion(center: CLLocation)
}
class LocationService: NSObject {
var locationManager = CLLocationManager()
weak var delegate: LocationServiceDelegate?
override init() {
super.init()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
private func checkAuthorizationStatus() {
switch CLLocationManager.authorizationStatus() {
case .notDetermined:
locationManager.requestAlwaysAuthorization()
case .denied:
delegate?.authorizationDenied()
case .authorizedAlways, .authorizedWhenInUse:
startUpdatingLocation()
default:
break
}
}
private func startUpdatingLocation() {
locationManager.startUpdatingLocation()
}
}
extension LocationService: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
checkAuthorizationStatus()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
locationManager.stopUpdatingLocation()
if let location = locations.last {
delegate?.setMapRegion(center: location)
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error.localizedDescription)
}
}
The method was originally called in viewDidLoad so the map would center on the user's location, so I moved it to viewDidAppear, but I still get the same notice when the app launches.
How do I delay the permission request until the user actually taps on the map tab - in this case the DIY Stores tab?

Setting map along with user current location for osx

Greeting pros,
As I know we can make a map by using google map api for IOS like the code below here.
import UIKit
import GoogleMaps
/* For cocoa:
Import Cocoa
Import MapKit
*/
class ViewController: NSViewController, CLLocationManagerDelegate {
#IBOutlet var mapView: MKMapView!
var locationManager = CLLocationManager()
var didFindMyLocation = false
var strForCurLatitude = "";
var strForCurLongitude = "";
var currentLocation = locManager.location!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
print("User allowed us to access location")
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error while get location \(error)")
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location: CLLocation? = locationManager.location
let coordinate: CLLocationCoordinate2D? = location?.coordinate
print(coordinate!)
print(coordinate!.latitude)
print(coordinate!.longitude)
strForCurLatitude = "\(coordinate!.latitude)"
strForCurLongitude = "\(coordinate!.longitude)"
let camera = GMSCameraPosition.camera(withLatitude: coordinate!.latitude, longitude: coordinate!.longitude, zoom: 15)
let mapView = GMSMapView.map(withFrame: .zero, camera: camera)
mapView.isMyLocationEnabled = true
self.view = mapView
let marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(coordinate!.latitude, coordinate!.longitude)
marker.map = mapView
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
But when I tried the similar method for osx (The difference is that I am using mapkit instead of google map), it says requestWhenInUseAuthorization()' is unavailable. I red this thread How to get user location ? [macOS] but it seems goes without clear resolved whether it is available to get current location for osx or not. So is it inaccessible to get current location for macOS/cocoa app? If it is not, then how to get current location in cocoa app?
I am pretty sure that many xcode programmers like me tried to solve this problem. Any answer you will get big appreciation tho. :)
requestWhenInUseAuthorization is unavailable on macOS.
Here's the source for a NSViewController subclass that checks for location manager and the current location successfully in Xcode 10.1 on macOS 10.13.6:
import Cocoa
import MapKit
import CoreLocation
class MapViewController: NSViewController, CLLocationManagerDelegate {
#IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager,
didChangeAuthorization status: CLAuthorizationStatus) {
print("location manager auth status changed to:" )
switch status {
case .restricted:
print("status restricted")
case .denied:
print("status denied")
case .authorized:
print("status authorized")
let location = locationManager.location
print("location: \(String(describing: location))")
case .authorizedAlways:
print("status authorized always")
case .notDetermined:
print("status not yet determined")
}
}
func locationManager(_ manager: CLLocationManager,
didFailWithError error: Error) {
print( "location manager failed with error \(error)" )
}
}
works for me on macOS if you say yes to the "enable location services" prompt when you launch the app the first time.
Note you also need the NSLocationWhenInUseUsageDescription property list entry as indicated in the documentation.
console output is (slightly obfuscated):
location manager auth status changed to: status not yet determined
location manager auth status changed to: status authorized location:
Optional(<+4X.48,-12X.62632228> +/- 65.00m (speed -1.00 mps /
course -1.00) # 11/3/18, 11:42:48 AM Pacific Daylight Time)

Error with NSBundle.mainBundle when adding sound

I've trying to create a simple sound board for when a button is pressed a sound is made, however when I used this code
let url = NSURL(fileURLWithPath: Bundle.mainBundle().pathForResource(sound, ofType: "mp3")!)
let audioPlayer = try AVAudioPlayer(contentsOfURL: url)
I get an error with "Bundle.mainBundle" orginally it told me to change "Bundle" from "NSBundle" because it has be renamed but when I correct that I get another error saying "Cannot call value for non-function type 'Bundle' "
my entire code:
import UIKit
import AVFoundation
class ViewController: UIViewController {
let soundFilenames = ["60gs", "check", "dada", "danceforme", "eat", "gods", "irelandbaby", "ko'd", "lefthand", "littlewerp", "nocalls", "precision", "sundaymorning", "surprise", "whothefuckisthatguy", "youlldonothing"]
var audioPlayers = [AVAudioPlayer]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for sound in soundFilenames {
do {
let url = Bundle.main.url(forResource:sound, withExtension: "mp3")!
let audioPlayer = try AVAudioPlayer(contentsOfURL: url)
audioPlayer.append(audioPlayer())
}
catch {
audioPlayers.append(AVAudioPlayer())
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func buttonTapped(_ sender: UIButton) {
let audioPlayer = audioPlayers[sender.tag]
audioPlayer.play()
}
}
can anyone help me with this please.
First of all in Swift 3 mainBundle() became main but why not the real short way:
let url = Bundle.main.url(forResource:sound, withExtension: "mp3")!
And the init method has been renamed to
let audioPlayer = try AVAudioPlayer(contentsOf: url)
and change the next line to:
audioPlayers.append(audioPlayer)

Sent email, without confirmation using swift (OSX)

I cannot manage to send an email using Swift on OSX.
Its almost do the work, but don't sent the email, and on my personal computer, its opening Google Chrome for some raison.
Here is my code
import Cocoa
class ViewController: NSViewController, NSSharingServiceDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
#IBAction func mag(sender: AnyObject) {
let body = "BODY EMAIL"
let shareItems = [body] as NSArray
var service = NSSharingService(named: NSSharingServiceNameComposeEmail)
service?.delegate = self
service?.recipients = ["email#address.com"]
let subject = "Subject!"
service?.subject = subject
service?.performWithItems(shareItems as [AnyObject])
}
}

I am setting up my sign up and login page using parse on xcode with swift but i keep getting a fatal error. Can somebody see what im doing wrong?

this is what i have so far:
import Foundation
import Parse
import UIKit
import Bolts
class SignUpViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var statusLabel: UILabel!
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var createAccountButton: UIButton!
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
emailTextField.delegate = self;
passwordTextField.delegate = self;
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func createAccountButtonPressed(sender: AnyObject) {
if verifyEmailDomain(self.emailTextField.text)
{
createAccount(self.emailTextField.text, password: self.passwordTextField.text)
}
else
{
//self.statusLabel.text = "Email domain is not valid.";
let alert = UIAlertView()
alert.title = "Invalid Email Domain"
alert.message = "Make sure you entered in your address correctly. If you did, ask your system about using PageMD! Thanks."
alert.addButtonWithTitle("Close")
alert.show()
}
}
func verifyEmailDomain(email: String) -> Bool
{
var isVerifiedDomain = false
let userDomain: String = (email.componentsSeparatedByString("#")).last!
//NSLog(userDomain)
let validDomainsFileLocation = NSBundle.mainBundle().pathForResource("ValidDomains", ofType: "txt")
var validDomainsFileContent = NSString(contentsOfFile: validDomainsFileLocation!, encoding: NSUTF8StringEncoding, error: nil)
// NSLog(validDomainsFileContent! as String)
let validDomains = validDomainsFileContent!.componentsSeparatedByString("\n")
for domain in validDomains
{
NSLog(domain as! NSString as String)
if userDomain == (domain as? NSString)
{
isVerifiedDomain = true
break
}
}
return isVerifiedDomain
}
func createAccount(email: String, password: String)
{
var newUser = PFUser()
newUser.username = email // We want the user to login only with their email.
newUser.email = email
newUser.password = password
newUser.signUpInBackgroundWithBlock { (succeeded: Bool, error: NSError?) -> Void in
if error == nil
{
// Account created successfully!
if succeeded == true
{
self.statusLabel.text = "Account created!"
}
}
else
{
if let errorField = error!.userInfo
{
self.statusLabel.text = (errorField["error"] as! NSString) as String
}
else
{
// No userInfo dictionary present
// Help from http://stackoverflow.com/questions/25381338/nsobject-anyobject-does-not-have-a-member-named-subscript-error-in-xcode
}
}
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool
{
textField.resignFirstResponder()
return true;
}
}
when i run it i receive this in my terminal for xcode:
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
and highlighted in green is:
var validDomainsFileContent = NSString(contentsOfFile: validDomainsFileLocation!, encoding: NSUTF8StringEncoding, error: nil)
what can i do to avoid this error?
I'm trying to create a login that uses the emailVerified feature from parse but I keep receiving this error and cant save the email to the core or send the verification email to the user. What can i do to make this code work and stop the error from coming up?
In that case, the file at validDominsfileContent wasn't found. You need to make sure that the file is included in your Bundle.
To do that, open the Bundle-Resources:
Project > App target > Build Phases > Copy bundle resources
There you save your file. Now it should be found by Swift.

Resources