I recently decided to build an application using the Maps SDK from Google, but the problem is, when I open the view controller, it only let me click for the first item.
I cant find the solution using only the google documentation.
Anyone has a fix for this?
import UIKit
import GoogleMaps
import GooglePlaces
import GooglePlacePicker
class PlacePickerVC: UIViewController, CLLocationManagerDelegate, GMSMapViewDelegate, GMSAutocompleteViewControllerDelegate, UITextFieldDelegate {
let currentLocationMarker = GMSMarker()
var locationManager = CLLocationManager()
var local = ""
var morada = ""
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Teste"
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
let config = GMSPlacePickerConfig(viewport: nil)
let placePicker = GMSPlacePickerViewController(config: config)
placePicker.delegate = self
present(placePicker, animated: true, completion: nil)
}
// Handle the user's selection.
func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
//Display the places but only show
print("Place name: \(place.name)")
print("Place address: \(place.formattedAddress)")
print("Place attributions: \(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)
}
}
extension PlacePickerVC : GMSPlacePickerViewControllerDelegate {
func placePicker(_ viewController: GMSPlacePickerViewController, didPick place: GMSPlace) {
print("Place name \(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")
}
}
Numbers 1 2 and 3 can't be clicked.
Related
Im using event kit to create a reminder, but when I press add or cancel the window does not close. if I go into the calendars app I can see the item in there. I've tried adding "editviewDelegate = self" but I always get an error saying "Cannot assign value of type 'ViewController?' to type 'EKEventEditViewDelegate"
import UIKit
import EventKit
import EventKitUI
class ViewController: UIViewController, EKEventViewDelegate {
func eventViewController(_ controller: EKEventViewController, didCompleteWith action: EKEventViewAction) {
controller.dismiss(animated: true, completion: nil)
}
let store = EKEventStore()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addnew))
}
#objc func addnew() {
store.requestAccess(to: .event) { [weak self] success, error in
if success, error == nil {
DispatchQueue.main.async {
guard let store = self?.store else {return}
let othervc = EKEventEditViewController()
othervc.eventStore = store
othervc.event = EKEvent(eventStore: store)
self?.present(othervc, animated: true, completion: nil)
}
}
}
}
Swift 5.x iOS 14
Trying to Get GameKit Matchmaking, and almost there...but... my match seems to fail with this error message?
Run GameKit on two real devices logged into different IDs.
I get the gameKit matching interface up.
Find my peer, and invite? and get this error message ...
2021-08-26 16:29:01.361416+0200 Mutate[18060:12891141] [AXRuntimeCommon] Unknown client: FAQ
2021-08-26 16:29:01.705773+0200 FAQ[18060:12891041] [Match] Error sending dictionary {
bundleID = "ch.cqd.FAQ";
bundleVersion = 1;
isDevelopmentVersion = 1;
message = 0;
platform = 1;
shortBundleVersion = "1.0";
} to deviceID: 076731E70C32E9C1, error = Error Domain=GKDiscoveryManager Code=-1 "Peer does not exist" UserInfo={NSLocalizedDescription=Peer does not exist}
The invited one starts playing, but the one inviting get stuck waiting for a response? What am I missing?
class SimpleViewController: UIViewController {
and
extension SimpleViewController: GKMatchmakerViewControllerDelegate, GKMatchDelegate, UINavigationControllerDelegate, GKGameCenterControllerDelegate, GKLocalPlayerListener, GKInviteEventListener, GKTurnBasedEventListener {
Plus their methods...
Here is the code ...
class SimpleViewController: UIViewController {
let minPlayers = 2
let maxPlayers = 4
override func viewDidLoad() {
super.viewDidLoad()
GKLocalPlayer.local.authenticateHandler = { [self] gcAuthVC, error in
if GKLocalPlayer.local.isAuthenticated {
GKLocalPlayer.local.register(self)
print("Authenticated to Game Center!")
let request = GKMatchRequest()
request.minPlayers = minPlayers
request.maxPlayers = maxPlayers
request.inviteMessage = "Mutant Anyone?"
let vc = GKMatchmakerViewController(matchRequest: request)
vc!.delegate = self
present(vc!, animated: true)
This bit I am sure works... but
extension SimpleViewController: GKMatchmakerViewControllerDelegate, GKMatchDelegate, UINavigationControllerDelegate, GKGameCenterControllerDelegate, GKLocalPlayerListener, GKInviteEventListener, GKTurnBasedEventListener {
func matchmakerViewController(_ viewController: GKMatchmakerViewController, didFind match: GKMatch) {
self.dismiss(animated: true)
match.delegate = self
print("matchmakerViewController ")
}
func player(_ player: GKPlayer, didAccept invite: GKInvite) {
self.dismiss(animated: true, completion: {
print("player ",invite)
})
}
func matchmakerViewController(_ viewController: GKMatchmakerViewController, hostedPlayerDidAccept player: GKPlayer) {
print("matchmakerViewController")
self.dismiss(animated: true, completion: {
print("player ",player)
})
}
func matchmakerViewController(_ viewController: GKMatchmakerViewController, didFindHostedPlayers players: [GKPlayer]) {
print("matchmakerViewController")
self.dismiss(animated: true, completion: {
print("player ",players)
})
}
func matchmakerViewControllerWasCancelled(_ viewController: GKMatchmakerViewController) {
self.dismiss(animated: true)
print("matchmakerViewControllerWasCancelled")
}
func matchmakerViewController(_ viewController: GKMatchmakerViewController, didFailWithError error: Error) {
print("Matchmaker vc did fail with error: \(error.localizedDescription).")
}
}
I suspect the mistake is in here?
I'm trying to implement an autocomplete search on Google Maps that will show the location that the user selects on the map with a marker.
Search works fine. The problem is as follows. When I select a location from the search results, I get a GMSPlace object that has the correct name as the selected value, correct place ID (confirmed using this link), but incorrect coordinates (-180.0,-180.0, or the kCLLocationCoordinate2DInvalid constant). I tested this on multiple locations.
Most of this code was borrowed from documentation for the Places API.
import UIKit
import GoogleMaps
import GooglePlaces
class ViewController: UIViewController, UISearchBarDelegate {
#IBOutlet weak var mapContainer: UIView!
var mapView: GMSMapView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.mapView = GMSMapView(frame: self.mapContainer.frame)
self.view.addSubview(self.mapView)
}
// Code from https://developers.google.com/places/ios-sdk/autocomplete#add_an_autocomplete_ui_control
#IBAction func searchByAddress(_ sender: Any) {
// Present the Autocomplete view controller when the button is pressed.
let autocompleteController = GMSAutocompleteViewController()
autocompleteController.delegate = self
// Specify the place data types to return.
let fields: GMSPlaceField = GMSPlaceField(rawValue: UInt(GMSPlaceField.name.rawValue) |
UInt(GMSPlaceField.placeID.rawValue))!
autocompleteController.placeFields = fields
// Display the autocomplete view controller.
present(autocompleteController, animated: true, completion: nil)
}
}
extension ViewController: GMSAutocompleteViewControllerDelegate {
// Handle the user's selection.
func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
let position: CLLocationCoordinate2D = place.coordinate
let camera = GMSCameraPosition.camera(withLatitude: position.latitude, longitude: position.longitude, zoom: 10)
let newMapView = GMSMapView.map(withFrame: self.mapContainer.frame, camera: camera)
self.mapView = newMapView
self.view.addSubview(newMapView)
let marker = GMSMarker()
marker.position = position
marker.title = place.name
marker.map = self.mapView
viewController.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) {
viewController.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
}
}
Any help would be appreciated!
I was facing the same issue and went through the Place SDK documentation which says clearly that we should define before hand to the GMSPlaceField of what details do we need exactly and if you had followed the doc completely, it would be resulting only in the name and placeId being populated.
So while instantiating your GMSAutoCompleteViewController define in the following way.
**let fields: GMSPlaceField = GMSPlaceField(rawValue:UInt(GMSPlaceField.name.rawValue) |
UInt(GMSPlaceField.placeID.rawValue) |
UInt(GMSPlaceField.coordinate.rawValue) |
GMSPlaceField.addressComponents.rawValue |
GMSPlaceField.formattedAddress.rawValue)!
autocompleteController.placeFields = fields**
I'm having this issue in Xcode 7.3.1. I'm essentially adding a search bar to a map. Here's the first part of the code for context:
import UIKit
import MapKit
class FirstViewController: UIViewController, UISearchBarDelegate {
var searchController:UISearchController!
var annotation:MKAnnotation!
var localSearchRequest:MKLocalSearchRequest!
var localSearch:MKLocalSearch!
var localSearchResponse:MKLocalSearchResponse!
var error:NSError!
var pointAnnotation:MKPointAnnotation!
var pinAnnotationView:MKPinAnnotationView!
#IBAction func showSearchBar(sender: AnyObject) {
searchController = UISearchController(searchResultsController: nil)
searchController.hidesNavigationBarDuringPresentation = false
self.searchController.searchBar.delegate = self
presentViewController(searchController, animated: true, completion: nil)
}
#IBOutlet var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
let initialLocation = CLLocation(latitude: 47.6062, longitude: -122.3321)
let regionRadius: CLLocationDistance = 1000
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius * 2.0, regionRadius * 2.0)
mapView.setRegion(coordinateRegion, animated: true)
}
centerMapOnLocation(initialLocation)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
Here's the snippet where the error occurs:
func searchBarSearchButtonClicked(searchBar: UISearchBar){
searchBar.resignFirstResponder()
dismissViewControllerAnimated(true, completion: nil)
if self.mapView.annotations.count != 0{
annotation = self.mapView.annotations[0]
self.mapView.removeAnnotation(annotation)
}
localSearchRequest = MKLocalSearchRequest()
localSearchRequest.naturalLanguageQuery = searchBar.text
localSearch = MKLocalSearch(request: localSearchRequest)
localSearch.start{ (localSearchResponse, error) -> Void in
if localSearchResponse == nil{
let alertController = UIAlertController(title: nil, message: "Place Not Found", preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil))
self.present(alertController, animated: true, completion: nil)
return
At localSearch.start, I am getting:
"Value of type MKLocalSearch has no member start"
I'm fairly new to Swift and pretty confused as to what the error is.
I also get:
"expected separator ",""
in the 3rd to last line. But even when changing it, error continues to occur. Could the two be related?
Since you are using older version of swift (swift 2.2) so I think you need to
replace
localSearch.start { ... //this is for swift 3
with
localSearch.startWithCompletionHandler { ... //this is for swift 2.2
For the error , of separator try this:
UIAlertActionStyle.Default
instead of
UIAlertActionStyle.default
Note : I think you also need to change UIAlertControllerStyle.alert to UIAlertControllerStyle.Alert
I am trying to add a send email button to a Sprite Kit game. I can get the email dialog to show up. But if I hit cancel, the app will crash or do nothing. If I hit send, the email will send, but the dialog stays. I cannot get the mailComposeController function to fire...please help!
Code:
import Foundation
import UIKit
import MessageUI
class MailViewController: UIViewController, MFMailComposeViewControllerDelegate {
let systemVersion = UIDevice.currentDevice().systemVersion
let devicemodel = UIDevice.currentDevice().model
let appVersion = NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] as! String
let appBuild = NSBundle.mainBundle().infoDictionary?["CFBundleVersion"] as! String
let myrootview2 = UIApplication.sharedApplication().keyWindow?.rootViewController
let mailComposerVC = MFMailComposeViewController()
override func viewDidLoad() {
super.viewDidLoad()
}
func sendEmailButtonTapped(sender: AnyObject) {
let mailComposeViewController = configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
self.view.window?.rootViewController = mailComposerVC
print("This is the rootview2: \(myrootview2)")
myrootview2!.presentViewController(mailComposeViewController, animated: true, completion: nil)
} else {
self.showSendMailErrorAlert()
}
}
func configuredMailComposeViewController() -> MFMailComposeViewController {
var msgbody: String
mailComposerVC.mailComposeDelegate = self
msgbody = "\n\nDevice: \(devicemodel)\niOS Version: \(systemVersion)\nApp Version: \(appVersion)\nApp Build Number: \(appBuild)\n"
mailComposerVC.setToRecipients(["test1#test.com"])
mailComposerVC.setSubject("test subject")
mailComposerVC.setMessageBody(msgbody, isHTML: false)
//print(mailComposerVC)
return mailComposerVC
}
func showSendMailErrorAlert() {
let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK")
sendMailErrorAlert.show()
}
// THIS DOESN'T GET CALLED WHEN SENDING OR CANCELLING EMAIL!
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
let test1 = result.rawValue
print(test1)
print(controller)
print(self)
print(myrootview2)
}
The issue is you are making the mailVC as the root view, you have to present it on your view like given below
#IBAction func sendEmailButtonTapped(sender: AnyObject) {
let mailComposeViewController = configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
self.presentViewController(mailComposeViewController, animated: true, completion: nil)
} else {
self.showSendMailErrorAlert()
}
}
func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
controller.dismissViewControllerAnimated(true, completion: nil)
}