issue with alamofire pod on xcode 9 - ios

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:

Related

How to determine when a user has succesfully logged in using FirebaseUI in swift?

To log a user in using the firebaseUI library you can do the following:
let authUI = FUIAuth.defaultAuthUI()
guard authUI != nil else {
return
}
authUI?.providers = [
FUIEmailAuth(), //works
FUIGoogleAuth(), //works
FUIOAuth.appleAuthProvider() //does not work
]
authUI?.delegate = self
authUI?.shouldHideCancelButton = true
let authViewController = authUI!.authViewController()
authViewController.modalPresentationStyle = .overCurrentContext
self.present(authViewController, animated: true, completion: nil)
and according to the documentation you include the following function on completion of user log in:
func authUI(_ authUI: FUIAuth,didSignInWith authDataResult: AuthDataResult?, error: Error?) {
if let user = authDataResult?.user{
print("Nice! You've signed in as \(user.uid)")
performSegue(withIdentifier: K.welcomeSegue, sender: self)
}
}
However, in my code, when I use the Apple sign-in option this function never runs. Do I need to call this function somewhere? If so how do I call it?
Here is the full code to my view controller:
class WelcomeViewController: UIViewController, FUIAuthDelegate {
#IBOutlet weak var titleLabel: UILabel!
override func viewWillAppear(_ animated: Bool){
if(Auth.auth().currentUser != nil){
self.performSegue(withIdentifier: K.welcomeSegue, sender: self)
}
}
#IBAction func loginPressed(_ sender: UIButton) {
let authUI = FUIAuth.defaultAuthUI()
guard authUI != nil else {
return
}
authUI?.providers = [
FUIEmailAuth(),
FUIGoogleAuth(),
FUIOAuth.appleAuthProvider()
]
authUI?.delegate = self
authUI?.shouldHideCancelButton = true
let authViewController = authUI!.authViewController()
authViewController.modalPresentationStyle = .overCurrentContext
self.present(authViewController, animated: true, completion: nil)
}
func authUI(_ authUI: FUIAuth,didSignInWith authDataResult: AuthDataResult?, error: Error?) {
if let user = authDataResult?.user{
print("Nice! You've signed in as \(user.uid)")
performSegue(withIdentifier: K.welcomeSegue, sender: self)
}
}
}

User variable is nil when creating a user with Firebase

I am following a tutorial and cannot seem to register my user as the user variable in the Firebase .createUser method appears to be nil. Therefore, when I unwrap it, I get an error.
I have read through a lot of the documentation as well as checked many other questions similar to mine but nothing seems to work
import UIKit
import Firebase
import SwiftKeychainWrapper
class ViewController: UIViewController {
#IBOutlet weak var userImgView: UIImageView!
#IBOutlet weak var usernameField: UITextField!
#IBOutlet weak var emailField: UITextField!
#IBOutlet weak var passwordField: UITextField!
var imagePicker: UIImagePickerController!
var selectedImage: UIImage!
override func viewDidLoad() {
super.viewDidLoad()
imagePicker = UIImagePickerController()
imagePicker.allowsEditing = true
imagePicker.delegate = self
}
override func viewDidAppear(_ animated: Bool) {
if let _ = KeychainWrapper.standard.string(forKey: "uid") {
self.performSegue(withIdentifier: "toFeed", sender: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupUser(userUid: String) {
if let imageData = self.userImgView.image!.jpegData(compressionQuality: 0.2) {
let imgUid = NSUUID().uuidString
let metaData = StorageMetadata()
Storage.storage().reference().child(imgUid).putData(imageData, metadata: metaData) { (metadata, error) in
let downloadURL = metadata
let userData = [
"username": self.usernameField.text!,
"userImg": downloadURL!
] as [String : Any]
Database.database().reference().child("users").child(userUid).setValue(userData)
self.performSegue(withIdentifier: "toFeed", sender: nil)
}
}
}
#IBAction func signInPressed(_ sender: Any) {
if let email = emailField.text, let password = passwordField.text {
Auth.auth().signIn(withEmail: email, password: password) { user, error in
if error != nil && !(self.usernameField.text?.isEmpty)! {
Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
self.performSegue(withIdentifier: "toFeed", sender: nil)
let userID = (user?.user.uid)!
self.setupUser(userUid: userID)
KeychainWrapper.standard.set(userID, forKey: "uid")
}
} else {
if let userID = (user?.user.uid) {
KeychainWrapper.standard.set((userID), forKey: "uid")
self.performSegue(withIdentifier: "toFeed", sender: nil)
}
}
}
}
}
#IBAction func getPhoto (_ sender: AnyObject) {
present(imagePicker, animated: true, completion: nil)
}
}
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
internal func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[.originalImage] as? UIImage {
userImgView.image = image
} else {
print("image wasnt selected")
}
imagePicker.dismiss(animated: true, completion: nil)
}
}
The error I am getting is one the "let userID = (user?.user.uid)!". It is
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
The completion block for createUser(withEmail:,password:) gets called with either a AuthResult.user or an error. That why, as Joshua commented, you should check if error is nil before accessing any of the user properties.
From the auth quickstart for Swift:
Auth.auth().createUser(withEmail: email, password: password) { authResult, error in
strongSelf.hideSpinner {
guard let user = authResult?.user, error == nil else {
strongSelf.showMessagePrompt(error!.localizedDescription)
return
}
print("\(user.email!) created")
strongSelf.navigationController?.popViewController(animated: true)
}
}

Google pick location for 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"
}
}

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)
}

how can I use a variable from another function swift?

I have a variable by the name of email in the contact picker function. I am trying to use that variable in the IBAction function for the MFMailComposeViewController. I want to apply it to toRecipient. How would I go about using a variable from another function?
import UIKit
import Contacts
import ContactsUI
import MessageUI
class ViewController: UIViewController, CNContactPickerDelegate, MFMailComposeViewControllerDelegate, UITextFieldDelegate {
//Message Setup
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var companyTextField: UITextField!
#IBOutlet weak var lblDetails: UILabel!
#IBAction func btnSelectEmployee(_ sender: Any) {
let entityType = CNEntityType.contacts
let authStatus = CNContactStore.authorizationStatus(for: entityType)
if authStatus == CNAuthorizationStatus.notDetermined {
let contactStore = CNContactStore.init()
contactStore.requestAccess(for: entityType, completionHandler: { (success, nil) in
if success {
self.openContacts()
}
else {
print("Not Authorized")
}
})
}
else if authStatus == CNAuthorizationStatus.authorized {
self.openContacts()
}
}
func openContacts() {
let contactPicker = CNContactPickerViewController.init()
contactPicker.delegate = self
self.present(contactPicker, animated: true, completion: nil)
}
func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
picker.dismiss(animated: true) {
}
}
func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
//When user select any contact
let fullName = "\(contact.givenName) \(contact.familyName)"
var email = "Not Available"
if !contact.emailAddresses.isEmpty {
let emailString = (((contact.emailAddresses[0] as AnyObject).value(forKey: "labelValuePair") as AnyObject).value(forKey: "value"))
email = emailString! as! String
self.lblDetails.text = "\(fullName)\n \(email)"
}
}
//Mail View
#IBAction func sendAction(_ sender: Any) {
let mailVC = MFMailComposeViewController()
mailVC.mailComposeDelegate = self
mailVC.setSubject("Hello. You have a visitor in the lobby.")
let mailContent = "\(nameTextField.text!) from \(companyTextField.text!) is here to see you."
mailVC.setMessageBody(mailContent, isHTML: false)
let toRecipient = "somebody5555555#gmail.com"
mailVC.setToRecipients([toRecipient])
self.present(mailVC, animated: true) {
self.nameTextField.text = ""
self.companyTextField.text = ""
}
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion: nil)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
nameTextField.resignFirstResponder()
companyTextField.resignFirstResponder()
return true
}
}
Define the var outside the function
var email = "Not Available"
func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
//When user select any contact
let fullName = "\(contact.givenName) \(contact.familyName)"
if !contact.emailAddresses.isEmpty {
let emailString = (((contact.emailAddresses[0] as AnyObject).value(forKey: "labelValuePair") as AnyObject).value(forKey: "value"))
email = emailString! as! String
self.lblDetails.text = "\(fullName)\n \(email)"
}
}
Now you can use the variable inside your class wherever you want.
To get more basics, read documentation Apple Documentation

Resources