SWIFT Delegate finishedWithAuth - iphone

i am new to swift and tried to implement Google Auth with GPPSignInDelegate. I get the sign in dialog but the delegate methods:
- didDisconnectWithError
- finishedWithAuth
are never called. Maybe I am doing something wrong. I tried to translate it so swift and it looks ok, but something is not working. Any suggestions? Thanks for your help in advance.
class LoginViewController: UIViewController, GPPSignInDelegate {
var kClientID = "XYZ"
#IBOutlet weak var loginButton: UIButton!
#IBOutlet var gppsloginButton: GPPSignInButton!
var signIn = GPPSignIn.sharedInstance()
override func viewDidLoad() {
super.viewDidLoad()
//var signIn = GPPSignIn.sharedInstance()
signIn.clientID = kClientID;
signIn.scopes = [kGTLAuthScopePlusLogin]
signIn.delegate = self
signIn.authenticate()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func finishedWithAuth(auth: GTMOAuth2Authentication, error: NSError ) -> Void{
debugPrintln("TEST")
}
func didDisconnectWithError ( error: NSError) -> Void{
debugPrintln("TEST2")
}

I think you missed to add the GPPURLHandler from your app delegate's URL handler in your AppDelegate.swift .
This handler will properly handle the URL that your application receives at the end of the authentication process.
func application(application: UIApplication, openURL url: NSURL, sourceApplication: NSString?, annotation: AnyObject) -> Bool {
return GPPURLHandler.handleURL(url, sourceApplication: sourceApplication, annotation:annotation)
}

Related

how to declare NFCReadersession variable in main class when NFC delegate method are implemented using extension?

Well, I need to add NFC functionality to a project and for this I am using CoreNFC. There is a condition that I need to add NFC functions using extension as below:
extension scanVC: NFCNDEFReaderSessionDelegate {
func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
}
func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
}
}
and rest of the code of view controller scanVC is also implemented using extensions like so:
extension scanVC {
override func viewDidLoad() {
super.viewDidLoad()
//viewDidLoad code here
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//viewWillAppear Code here
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// viewWillDisappear code here
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
//viewDidDisappear code here
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// code here
}
}
extension scanVC: SubmitForm {
// some other functionalities
}
// *** main class with some variable and outlets declaration ***
class scanVC: UIViewController {
#IBOutlet var headerScanLabel: UILabel!
#IBOutlet var scanView: UIView!
#IBOutlet var scanLabel: UILabel!
#IBOutlet var submitBtn: UIButton!
}
well now the problem is I need to declare one or more session variables in this main scanVC, but when I declare it gives me an error relating #available as:
" 'NFCReaderSession' is only available on iOS 11.0 or newer "
if I fix it adding "#available(iOS 11.0, *)" to its enclosing class then the extension with viewdidload,viewWillappear etc gives this error :
"Overriding 'viewDidLoad' must be as available as declaration it overrides"
I have spent almost a day to fix but nothing worked... any suggestion??
Xcode 10.2, swift 4. thanks!!
Well the solution was easy... I just declared those required variable out of class.. just below import statement. And they are accessible in all extension blocks.
//***********NFC REQUIRED VARIABLES *************
#available(iOS 11.0, *)
var nfcsession:NFCNDEFReaderSession?
#available(iOS 11.0, *)
var detectedMessages = [NFCNDEFMessage]()
#available(iOS 11.0, *)
var payloads = [NFCNDEFPayload]()
//************************************************

URL validation not working in swift

started learning swift two weeks ago, with no previous programming experience, and I can't for the life of me figure out why this wouldn't work to check for nil. it just crashes when trying to load a web page if the user enters an invalid URL. This is the ENTIRETY of the code.
import UIKit; import WebKit
class ViewController: UIViewController {
#IBOutlet weak var adressBar: UITextField!
#IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func returnPressed(_ sender: Any) {
if let adressBarText = adressBar.text {
if let myURL = URL(string: adressBarText) {
let myRequest = URLRequest(url: myURL)
webView.load(myRequest)
adressBar.resignFirstResponder()
print("EYYYYY")
} else {
print("BOOOO")
}
}
}
}
Try this method
func verifyUrl (urlString: String?) -> Bool {
//Check for nil
if let urlString = urlString {
// create NSURL instance
if let url = NSURL(string: urlString) {
// check if your application can open the NSURL instance
return UIApplication.sharedApplication().canOpenURL(url)
}
}
return false
}
https://stackoverflow.com/a/30130535/8069241

Database Reference Error

In my iOS project, I am using Firebase to create a real time database. I have already imported it in the AppDelegate.swift.
When trying to reference my database within the app, an error appears.
Any ideas on how to fix this? Here is the code:
import UIKit
import Firebase
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
post()
}
func post(){
let title = "Title"
let message = "Message"
let post : [String : AnyObject] = ["title" : title as AnyObject,
"message" : message as AnyObject]
let databaseRef = FirebaseApp.database().reference()
databaseRef.child("Posts").childByAutoId().setValue(post)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You need to first configure firebase, example:
FirebaseApp.configure()
then you can reference to the database:
let databaseRef = Database.database().reference()
FirebaseApp does not contain a method called database()
If your Firebase/Database version is 4.9.0, the following should give you a good start.
import UIKit
import Firebase
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
override init() {
super.init()
FirebaseApp.configure()
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
return true
}
}
import UIKit
import FirebaseDatabase
class TableViewController: UITableViewController {
// MARK: - Instance variables
var databaseRef: DatabaseReference!
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
//getting a reference to the node artists
databaseRef = Database.database().reference()
}
}
Add 'Firebase/Database' to your pods:
pod 'Firebase/Core'
pod 'Firebase/Database'
Then update the pods
pod install
Into your code be sure to import firebase
import Firebase
And use it as
FirebaseApp.configure()
var ref: DatabaseReference!
ref = Database.database().reference()
ref.setValue("Testing")
More info on Firebase help

Parse PFUser not registering subclass

I am trying to use Parse PFUser in a software for OSX desktop. When I try to use it PFUser.query() it gives a message: Failed to set (contentViewController) user defined inspected property on (NSWindow): The class PFUser must be registered with registerSubclass before using Parse.
It is happening without registering the class.
I tried it registering the class this way: PFUser.registerSubclass() but it still doesn't work.
I will use the default PFUser without adding any fields to it, so I don't need to create a custom class to be my PFUser.
I tried to use PFUser.enableAutomaticUser() without success
Code below:
AppDelegate.swift
import Cocoa
import Parse
import Bolts
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
let APP_ID = "app_id"
let CLIENT_KEY = "client_key"
let SERVER = "https://parseserver.com/"
func applicationDidFinishLaunching(_ aNotification: Notification) {
PFUser.registerSubclass()
let configuracaoParse = ParseClientConfiguration {
$0.applicationId = self.APP_ID
$0.clientKey = self.CLIENT_KEY
$0.server = self.SERVER
}
Parse.initialize(with: configuracaoParse)
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
ViewController.swift
import Cocoa
import Parse
class ViewController: NSViewController {
#IBOutlet weak var emailTextField: NSTextField!
#IBOutlet weak var senhaSecureTextField: NSSecureTextField!
override func viewDidLoad() {
super.viewDidLoad()
contaUsuarios()
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
#IBAction func entrarButtonClicked(_ sender: NSButton) {
}
func contaUsuarios() {
let query = PFUser.query()
query?.countObjectsInBackground(block: {
(count, error) -> Void in
let numeroUsers = Int(UInt32(count))
if numeroUsers > 0 {
}
print(numeroUsers)
})
}
}
Reading some content on the internet I discovered that in OSX the ViewController is launched before the AppDelegate finishes loading, so I initialized the Parse connection and subclassing in the ViewController's viewDidLoad instead of AppDelegate and it is working just fine.

ios 8 and Swift: call a function in another class from view controller

I want to touch a button in ViewController and run a simple function in a custom class. No parameters needed. Code is basically:
class MyClass: UIView {
//init function is here
//other setup stuff
...
func SetFocus() {
//I want to set the camera focus to infinity.
var error: NSErrorPointer = nil
var pos: CFloat = 1.0
captureDevice!.lockForConfiguration(error)
captureDevice!.setFocusModeLockedWithLensPosition(pos, completionHandler: nil)
captureDevice!.unlockForConfiguration()
}
}
and in ViewController
import UIKit
class ViewController: UIViewController {
#IBOutlet var myClass: MyClass!
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 myButton(sender: UIButton) {
myClass.SetFocus()
}
}
I've tried everything I can think of (new at Swift) and the app either crashes or the function I'm calling doesn't run. Everything else in MyClass works OK.
Try to delete the #IBOutlet from before MyClass.
var myClass : MyClass!
You can also try this:
var myClass : MyClass! = MyClass()
From the looks of it, however, everything you are doing in setFocus() in MyClass, can easily be recreated in the ViewController.
Try this
#IBAction func myButton(sender: UIButton) {
var ClassViewController = self.storyboard.instantiateViewControllerWithIdentifier("StoryboardID") as! UIViewController
ClassViewController.MyFunction()
}