Google pick location for iOS - ios

I read this and tried to build a location picker app, where the below code worked perfectly:
import UIKit
import GooglePlacePicker
class ViewController: UIViewController {
// Add a pair of UILabels in Interface Builder, and connect the outlets to these variables.
#IBOutlet var nameLabel: UILabel!
#IBOutlet var addressLabel: UILabel!
// Add a UIButton in Interface Builder, and connect the action to this function.
#IBAction func pickPlace(_ sender: UIButton) {
let center = CLLocationCoordinate2D(latitude: 37.788204, longitude: -122.411937)
let northEast = CLLocationCoordinate2D(latitude: center.latitude + 0.001, longitude: center.longitude + 0.001)
let southWest = CLLocationCoordinate2D(latitude: center.latitude - 0.001, longitude: center.longitude - 0.001)
let viewport = GMSCoordinateBounds(coordinate: northEast, coordinate: southWest)
let config = GMSPlacePickerConfig(viewport: viewport)
let placePicker = GMSPlacePicker(config: config)
placePicker.pickPlace(callback: {(place, error) -> Void in
if let error = error {
print("Pick Place error: \(error.localizedDescription)")
return
}
if let place = place {
self.nameLabel.text = place.name
self.addressLabel.text = place.formattedAddress?.components(separatedBy: ", ")
.joined(separator: "\n")
} else {
self.nameLabel.text = "No place selected"
self.addressLabel.text = ""
}
})
}
}
Apparently the GMSPlacePicker is deprecated, and replaced by GMSPlacePickerViewController, so I tried the example here:
import UIKit
import GooglePlacePicker
class ViewController: UIViewController {
// Add a pair of UILabels in Interface Builder, and connect the outlets to these variables.
#IBOutlet var nameLabel: UILabel!
#IBOutlet var addressLabel: UILabel!
// The code snippet below shows how to create and display a GMSPlacePickerViewController.
#IBAction func pickPlace(_ sender: UIButton) {
let config = GMSPlacePickerConfig(viewport: nil)
let placePicker = GMSPlacePickerViewController(config: config)
present(placePicker, animated: true, completion: nil)
}
// To receive the results from the place picker 'self' will need to conform to
// GMSPlacePickerViewControllerDelegate and implement this code.
func placePicker(_ viewController: GMSPlacePickerViewController, didPick place: GMSPlace) {
// Dismiss the place picker, as it cannot dismiss itself.
viewController.dismiss(animated: true, completion: nil)
print("Place name \(place.name)")
print("Place address \(place.formattedAddress)")
print("Place attributions \(place.attributions)")
}
func placePickerDidCancel(_ viewController: GMSPlacePickerViewController) {
// Dismiss the place picker, as it cannot dismiss itself.
viewController.dismiss(animated: true, completion: nil)
print("No place selected")
}
}
But it is not functioning properly, am I missing anything here? The location picker is poping up, but neither the cancel button is clickable, nor the location picker is closed upon picking the required location, and accordingly nothing is printed!

Thanks for the comments from #tassinai below the full working code:
import UIKit
import GooglePlacePicker
class ViewController: UIViewController, GMSPlacePickerViewControllerDelegate {
#IBOutlet weak var placeNameLabel: UILabel!
#IBAction func placePicker(_ sender: Any) {
let config = GMSPlacePickerConfig(viewport: nil)
let placePicker = GMSPlacePickerViewController(config: config)
placePicker.delegate = self
present(placePicker, animated: true, completion: nil)
}
func placePicker(_ viewController: GMSPlacePickerViewController, didPick place: GMSPlace) {
viewController.dismiss(animated: true, completion: nil)
print("Place name \(place.name)")
placeNameLabel.text = place.name
}
func placePicker(_ viewController: GMSPlacePickerViewController, didFailWithError error: Error) {
// In your own app you should handle this better, but for the demo we are just going to log
// a message.
NSLog("An error occurred while picking a place: \(error)")
}
func placePickerDidCancel(_ viewController: GMSPlacePickerViewController) {
// Dismiss the place picker, as it cannot dismiss itself.
viewController.dismiss(animated: true, completion: nil)
print("No place selected")
placeNameLabel.text = "No place selected"
}
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.
}
}
Below another way of writing the above code:
import UIKit
import GooglePlacePicker
class ViewController: UIViewController {
#IBOutlet weak var placeNameLabel: UILabel!
#IBAction func placePicker(_ sender: Any) {
let config = GMSPlacePickerConfig(viewport: nil)
let placePicker = GMSPlacePickerViewController(config: config)
placePicker.delegate = self
present(placePicker, animated: true, completion: nil)
}
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.
}
}
extension ViewController : GMSPlacePickerViewControllerDelegate {
func placePicker(_ viewController: GMSPlacePickerViewController, didPick place: GMSPlace) {
viewController.dismiss(animated: true, completion: nil)
print("Place name \(place.name)")
placeNameLabel.text = place.name
}
func placePicker(_ viewController: GMSPlacePickerViewController, didFailWithError error: Error) {
// In your own app you should handle this better, but for the demo we are just going to log
// a message.
NSLog("An error occurred while picking a place: \(error)")
}
func placePickerDidCancel(_ viewController: GMSPlacePickerViewController) {
// Dismiss the place picker, as it cannot dismiss itself.
viewController.dismiss(animated: true, completion: nil)
print("No place selected")
placeNameLabel.text = "No place selected"
}
}

Related

issue with alamofire pod on xcode 9

hello everyone I install the alamofire and google places pod to autocomplete the places search
but it gives me the error:
The “Swift Language Version” (SWIFT_VERSION) build setting must be set to a
supported value for targets that use Swift. This setting can be set in the
build settings editor.
my code:
class SetLocationViewController: UIViewController {
private var placesClient = GMSPlacesClient()
#IBOutlet weak var setLocationTf: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
placesClient = GMSPlacesClient.shared()
}
#IBAction func onClickTf(_ sender: Any) {
setLocationTf.resignFirstResponder()
let acController = GMSAutocompleteViewController()
acController.delegate = self
let filter = GMSAutocompleteFilter()
filter.type = .establishment
filter.countries = ["BR"]
acController.autocompleteFilter = filter
let field: GMSPlaceField = [.name, .placeID]
acController.placeFields = field
present(acController, animated: true, completion: nil)
}
}
extension SetLocationViewController: GMSAutocompleteViewControllerDelegate {
func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
if let name = place.name {
setLocationTf.text = name
}
dismiss(animated: true, completion: nil)
}
func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
print("Error: ", error.localizedDescription)
}
func wasCancelled(_ viewController: GMSAutocompleteViewController) {
dismiss(animated: true, completion: nil)
}
}
The error I got:

How to get the google places automatically

I want display the Google Automatic places in Text field.
I write the following code but I unable to understand where the I give apikey.
Same time I getting the latitude and longitude also for selected address.
import UIKit
import GoogleMaps
import GooglePlaces
class ViewController: UIViewController ,UITextFieldDelegate,GMSAutocompleteViewControllerDelegate{
#IBOutlet weak var placeaddress: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let apikey = "API_KEY"
self.placeaddress.delegate = self
}
func textFieldDidBeginEditing(_ textField: UITextField) {
let acController = GMSAutocompleteViewController()
acController.delegate = self
self.present(acController, animated: true, completion: nil)
}
// Handle the user's selection.
func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
print("Place name: \(place.name)")
print("Place address: \(String(describing: place.formattedAddress))")
print("Place attributions: \(String(describing: place.attributions))")
dismiss(animated: true, completion: nil)
}
func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
// TODO: handle the error.
print("Error: ", error.localizedDescription)
}
// User canceled the operation.
func wasCancelled(_ viewController: GMSAutocompleteViewController) {
dismiss(animated: true, completion: nil)
}
}
First import Google Framework into appDelegate
import GoogleMaps
After that provide your api key into didFinishLaunchingWithOptions in appDelegate
GMSServices.provideAPIKey("Your API Key")
Hope this will help you.

Swift google autocomplete with local search

I am trying to do Google Autocomplete using Google Places in Swift 3.0. But I need to search depending upon my current location. Example, If I am in Kolkata, India and I type search keyword "Ko" it will show the results of Kolkata first .
Can anyone help me.
Here is my code.I import GooglePlaces in my class
#IBAction func txtFieldLocationDidStartEditing(_ sender: Any) {
self.placeAutocomplete()
}
func placeAutocomplete() {
let autocompleteController = GMSAutocompleteViewController()
autocompleteController.delegate = self
present(autocompleteController, animated: true, completion: nil)
}
// MARK: - autoComplete Delegates
func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
print("Place name: \(place.name)")
dismiss(animated: true, completion: nil)
}
func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
// TODO: handle the error.
print("Error: ", error.localizedDescription)
}
// User canceled the operation.
func wasCancelled(_ viewController: GMSAutocompleteViewController) {
dismiss(animated: true, completion: nil)
}
// Turn the network activity indicator on and off again.
func didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
func didUpdateAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
Please anyone help me to solve it out.
Thanks in advance.
The only API provided by GMSAutocompleteViewController is to set the GMSCoordinateBounds like so (reference):
func placeAutocomplete() {
let visibleRegion = mapView.projection.visibleRegion()
let bounds = GMSCoordinateBounds(coordinate: visibleRegion.farLeft, coordinate: visibleRegion.nearRight)
let autocompleteController = GMSAutocompleteViewController()
acController.autocompleteBounds = bounds
autocompleteController.delegate = self
present(autocompleteController, animated: true, completion: nil)
}

detect up volume change swift

I'm having problems detecting when someone presses up or down volume button. For the moment I just play a file but I want to know when the user presses the button to show an alert when the volume changes. I'm developing in Swift and I'm using AVFoundation to create this player. For the moment I can't find something that works in Swift. I'm very new to this language.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var backgroundMusicPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
playBackgroundMusic("IronBacon.mp3")
}
func playBackgroundMusic(filename:String){
let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
print(url)
guard let newUrl = url else{
print("couldn't find file: \(filename)")
return
}
do{
backgroundMusicPlayer = try AVAudioPlayer(contentsOfURL: newUrl)
backgroundMusicPlayer.numberOfLoops = -1
backgroundMusicPlayer.prepareToPlay()
}catch let error as NSError{
print(error.description)
}
}
#IBAction func playPauseAction(sender: UIButton) {
sender.selected = !sender.selected
if sender.selected {
backgroundMusicPlayer.play()
} else {
backgroundMusicPlayer.pause()
}
}
func ShowAlert(title: String, message: String, dismiss: String) {
let alertController = UIAlertController(title: title, message:
message, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: dismiss, style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
func volumeUp(){
ShowAlert( "example", message: "example", dismiss: "close")
}
func volumeDown(){
ShowAlert( "example", message: "example", dismiss: "close")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
This should do the trick.
class ViewController: UIViewController {
// MARK: Properties
let notificationCenter = NSNotificationCenter.defaultCenter()
// MARK: Lifecycle
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
notificationCenter.addObserver(self,
selector: #selector(systemVolumeDidChange),
name: "AVSystemController_SystemVolumeDidChangeNotification",
object: nil
)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
notificationCenter.removeObserver(self)
}
// MARK: AVSystemPlayer - Notifications
func systemVolumeDidChange(notification: NSNotification) {
print(notification.userInfo?["AVSystemController_AudioVolumeNotificationParameter"] as? Float)
}
}
For some reason, the accepted answer does not work. Here is how you can do it in latest iOS versions -
func addObserver() {
NotificationCenter.default.addObserver(self,
selector: #selector(systemVolumeDidChange),
name: Notification.Name("SystemVolumeDidChange"),
object: nil)
}
func systemVolumeDidChange(notification: NSNotification) {
Log.msg("New Volume = \(notification.userInfo?["Volume"] as? Float)")
}
There are a few more fields in user info that can determine the volume change reason etc.

FirebaseViewController is black

when following the instructions for FirebaseUI to display the LoginViewController it only shows a black screen.
As you can see it kind of replaces the current viewcontroller instead of presenting it.
Here is the code from the presenting viewcontroller
import UIKit
import Firebase
import FirebaseUI
class FirstViewController: UIViewController {
#IBOutlet weak var logoutButton: UIButton!
var rootRef = Firebase(url: Constants.FireBaseUrl)
var loginViewController: FirebaseLoginViewController!
override func viewDidLoad() {
super.viewDidLoad()
loginViewController = FirebaseLoginViewController(ref: rootRef)
loginViewController.enableProvider(.Facebook)
loginViewController.enableProvider(.Password)
loginViewController.didDismissWithBlock { (user: FAuthData!, error: NSError!) -> Void in
if (user != nil) {
// user
} else if (error != nil) {
// error
} else {
// cancel
}
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if (loginViewController.currentUser() == nil) {
presentViewController(loginViewController, animated: true, completion: nil)
}
}
// MARK: - Actions
#IBAction func logoutTouched(sender: AnyObject) {
rootRef.unauth()
}
}

Resources