Search Google Places on tableView when textField is clicked in Swift 3? - swift3

How to Search Google Places when i click on textFieldand want to show results just below textField. I am using Swift 3.0 version.Could someone help me

First you need to install the GooglePlaces SDK in your project. Then you refer the code bellow.
in Swift 3
In AppDelegate
import UIKit
import CoreData
import GoogleMaps
import GooglePlacePicker
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
func setUpGoogleMaps()
return true
}
func setUpGoogleMaps() {
let googleMapsApiKey = "AIzaSyA-kiOBvrR9CNztqutwmKaSLyXIid93K0E"
GMSServices.provideAPIKey(googleMapsApiKey)
GMSPlacesClient.provideAPIKey("AIzaSyA-kiOBvrR9CNztqutwmKaSLyXIid93K0E")
}
In your ViewController which is having the textField
import UIKit
import GooglePlaces
import GoogleMaps
import GooglePlacePicker
class HotelVC: UIViewController, GMSMapViewDelegate, UITextFieldDelegate {
#IBOutlet weak var YourTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.YourTextField.delegate = self
}
func textFieldDidBeginEditing(_ textField: UITextField) {
let acController = GMSAutocompleteViewController()
acController.delegate = self
self.present(acController, animated: true, completion: nil)
}
}
extension viewController: GMSAutocompleteViewControllerDelegate {
func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
print("Place name: \(place.name)")
print("Place address: \(place.formattedAddress ?? "null")")
self.YourTextField.text = place.formattedAddress
print("Place attributions: \(String(describing: place.attributions))")
self.dismiss(animated: true, completion: nil)
}
func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
// TODO: handle the error.
// print("Error: \(error.description)")
self.dismiss(animated: true, completion: nil)
}
// User canceled the operation.
func wasCancelled(_ viewController: GMSAutocompleteViewController) {
print("Autocomplete was cancelled.")
self.dismiss(animated: true, completion: nil)
}
}

You will get location from the selected place. Try this code.
public func viewController(viewController: GMSAutocompleteViewController, didAutocompleteWithPlace place: GMSPlace) {
var lat = place.coordinate.latitude
var lon = place.coordinate.longitude
print("lat lon",lat,lon)
}

Related

The files are grayed out in UIDocumentPicker

I’m unable to select the document documents they are greyed out
I have tried with
UIDocumentPickerViewController - each file that was picked once is then grayed out
import UIKit
import MobileCoreServices
import UniformTypeIdentifiers
class ViewController: UIViewController, UINavigationControllerDelegate, UIDocumentPickerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func ShowPicker(_ sender: Any) {
let pickerViewController = UIDocumentPickerViewController(forOpeningContentTypes: [.pdf], asCopy: true)
pickerViewController.delegate = self
pickerViewController.allowsMultipleSelection = false
pickerViewController.shouldShowFileExtensions = true
present(pickerViewController, animated: true, completion: nil)
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
print("Cancelled")
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
print("didPickDocuments at \(urls)")
}
}

Custom UIViewController with UIViewcontrollerRepresentable that has a UITextView that crashes or is nil when called in SwiftUI

I have made a custom UIViewController called ViewControllerA and want to be able to use it so I made a UIViewControllerRepresentable called ViewControllerARepresentable as shown below, the problem though is that when I call ViewControllerARepresentable in my SwiftUI view and pass a value for stringToUpdateTextView, the ViewControllerA says the htmlTextView(UITextView) in ViewControllerA is nil and I'm not sure why.
ViewControllerARepresentable(stringToUpdateTextView: "<html>Send some Html Text as string here</html>")
ViewControllerARepresentable
public struct ViewControllerARepresentable: UIViewControllerRepresentable {
var stringToUpdateTextView: String
public func makeUIViewController(context: Context) -> ViewControllerA {
let viewcontrollerA = ViewControllerA(testString: testingString)
return viewcontrollerA
}
public func updateUIViewController(_ uiViewController: ViewControllerA, context: Context) {}
}
ViewControllerA
open class ViewControllerA: UIViewController {
public var stringToUpdateTextView: String
override open func viewDidLoad() {
super.viewDidLoad()
htmlTextView.text = stringToUpdateTextView
}
#IBOutlet weak var htmlTextView: UITextView!
public init(testString: String) {
self.testString = testString
super.init(nibName: nil, bundle: nil)
}
required public init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Crash occurs at htmlTextView.text = stringToUpdateTextView saying that htmlTextView.text is nil even though its an IBOutlet.
Any Change made to the htmlTextView like background color ,etc, also causes a crash if called in viewDidAppear or viewDidLoad
When instantiating your view controller in makeUIViewController, the outlets haven't been initialised yet.
The following code loads your view controller from the storyboard, and updates the properties in updateUIViewController:
ViewController.swift
import UIKit
import SwiftUI
class ViewController: UIViewController {
#IBOutlet weak var htmlTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
struct ViewControllerWrapper: UIViewControllerRepresentable {
typealias UIViewControllerType = ViewController
#Binding var text: String
func makeUIViewController(context: Context) -> ViewController {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
guard let viewController = storyboard.instantiateViewController(
identifier: "ViewController") as? ViewController else {
fatalError("Cannot load from storyboard")
}
return viewController
}
func updateUIViewController(_ uiViewController: ViewController, context: Context) {
uiViewController.htmlTextView.text = text
}
}
struct ViewControllerPreview: PreviewProvider {
static var previews: some View {
ViewControllerWrapper(text: .constant("hello world!"))
}
}
SwiftUIView.swift
struct SwiftUIView: View {
#State var text = "Text"
var body: some View {
HStack {
TextField("Text:", text: $text)
ViewControllerWrapper(text: $text)
}
}
}

Google place autocomplete API with SwiftUI

I am trying to implement auto search for address in my App using SwiftUI. Google tutorial are based on UIKit, I was hoping if someone has tried and can guide me to the right direction. Thanks
Try this code; it works for me.
import Foundation
import UIKit
import SwiftUI
import GooglePlaces
struct PlacePicker: UIViewControllerRepresentable {
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
#Environment(\.presentationMode) var presentationMode
#Binding var address: String
func makeUIViewController(context: UIViewControllerRepresentableContext<PlacePicker>) -> GMSAutocompleteViewController {
let autocompleteController = GMSAutocompleteViewController()
autocompleteController.delegate = context.coordinator
let fields: GMSPlaceField = GMSPlaceField(rawValue: UInt(GMSPlaceField.name.rawValue) |
UInt(GMSPlaceField.placeID.rawValue))!
autocompleteController.placeFields = fields
let filter = GMSAutocompleteFilter()
filter.type = .address
filter.country = "ZA"
autocompleteController.autocompleteFilter = filter
return autocompleteController
}
func updateUIViewController(_ uiViewController: GMSAutocompleteViewController, context: UIViewControllerRepresentableContext<PlacePicker>) {
}
class Coordinator: NSObject, UINavigationControllerDelegate, GMSAutocompleteViewControllerDelegate {
var parent: PlacePicker
init(_ parent: PlacePicker) {
self.parent = parent
}
func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
DispatchQueue.main.async {
print(place.description.description as Any)
self.parent.address = place.name!
self.parent.presentationMode.wrappedValue.dismiss()
}
}
func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
print("Error: ", error.localizedDescription)
}
func wasCancelled(_ viewController: GMSAutocompleteViewController) {
parent.presentationMode.wrappedValue.dismiss()
}
}
}

Unlapping optional error in UIView

I wanted to programmatically control the menu view so I tried the following:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var menuView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func menuBtn(_ sender: UIButton) {
print("menuBtn")
print(type(of: menuView!)) // <- `Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)`
}
}
And click the button, console says
fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)
Both are connected to ViewController.
How can I get print(type(of: menuView!))?
===============================================================
ps.
I've simplified my real problem. this is my real code:
button on ViewController.Swift
#IBAction func openModal(_ sender: UIButton) {
print("open btn clicked")
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "menuViewController") as! MenuViewController
self.addChildViewController(vc)
self.view.addSubview(vc.contentView!) /// <- This cause problem
}
MenuViewController.swift
import UIKit
class MenuViewController: UIViewController {
#IBOutlet weak var contentView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.clear
view.isOpaque = false
}
#IBAction func closeBtn(_ sender: UIButton) {
print("close btn clicked")
self.view.removeFromSuperview()
}
}
and Why I wan't using it:
I can't scrolling when menuView appeared.. I want to use the buttons in the menu view and scroll at the same time.

I got an error [Type "View Controller" does not conform to protocol "ORKTaskViewControllerDelegate"]

I am just starting to use swift3 in Xcode in order to utilize ResearchKit provided by Apple.inc.
Although I have worked through tutorials from Researchkit Tutorial with Swift: Getting started in Ray Wenderlich, I have a trouble in the extension of ViewController. The following is my code.
import ResearchKit
import UIKit
class ViewController: UIViewController {
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 consentTapped(sender : AnyObject) {
let taskViewController = ORKTaskViewController(task: ConsentTask, taskRun: nil)
taskViewController.delegate = self
present(taskViewController, animated: true, completion: nil)
}
}
extension ViewController: ORKTaskViewControllerDelegate {
func taskViewController(taskViewController: ORKTaskViewController, didFinishWithReason
reason: ORKTaskViewControllerFinishReason, error: NSError?) {
//Handle results with taskViewController.result
taskViewController.dismiss(animated:true, completion: nil)
}
}
You've missed to add delegate. Add ORKTaskViewControllerDelegate to ViewController
class ViewController: UIViewController,ORKTaskViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad(
}
}