Swift. Remember a facebook login - swift

Okay so I have implemented a facebook login button:
loginButton.readPermissions = ["public_profile", "email", "user_friends"]
loginButton.center = (self.view?.center)!
loginButton.delegate = self
self.view?.addSubview(loginButton)
but every time I shut down the app completely and turn it on again I need to rejoin, so my question is how an I make the app remember that I've already logged in once?

try using this
Put this code in your appDelegate
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if((FBSDKAccessToken.currentAccessToken()) != nil){
//user is sign in
//Put here something what you want to do if user is sign in
}
return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}

save the email or facebook token which you get from the facebook response in your Userdefaults or coredata..
then check for the value first in the login screen and direct your app..

Related

Update data in Table View after user received push notification

I have an app with push notifications and RealmDB. User himself chooses the date of notifications after that the notification date goes to the RealmDB. Every time a user receives a notification, the date of the next notification changes, and the user can see the date in Table View. Problem is...after the user has received the notification, he goes to the application through the push notification so func doesn't work. If user go to app by open it - everything is OK.
In cellForRowAt:
center.getDeliveredNotifications { (notifications) in
for notification:UNNotification in notifications {
print(notification.request.identifier)
if (notification.request.identifier == timeId){
let today = notification.date
let realNextDate = Calendar.current.date(byAdding: .day, value: timeInterval!, to: today)
let realm = try! Realm()
try! realm.write {
for plants in realm.objects(MyPlant.self).filter("id == %#", timeId as Any) {
plants.nextDate = realNextDate
plants.prevDate = today
}
}
}
}
}
The reason behind this I believe is that you are configuring Realm in the AppDelegate with
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
This is what is executed when you open the app by tapping on the App icon. In the case where you open the app by tapping the push notification, the above AppDelegate method isn't executed. Instead a method shown below is executed,
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
// unused
}
Due to this, you will have to do some configurations in this method as well for it to work when tapped on the notification.

How to detect if an app was opened by a notification action in the ViewController

I am working on a notification app and was wondering if it is possible to detect if the app is opened from a notification action in ViewController.Swift instead of the AppDelegate.swift. How can I do this?
Krish, Whenever the app is launched the AppDelegate gets called(if the default Main class is not modified) and in the AppDelegate class you can check for the launch option in launch option delegate whether its opened through remote notification. This is the first action where you will catch the app opening event.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let remoteNotif = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary
if remoteNotif != nil {
let notifName = remoteNotif?["aps"] as! String
print("Notification: \(notifName )")
}
else {
print("Not remote")
}
}
Here is a complete and easy answer to that
After you handle the event on AppDelegate you can use an observer to let your ViewController of that event.
Normally you should redirect the user to a specific view, depending on the notification payload.

Function that detects an app uninstall/reinstall

Been looking around to find a way to detect when an app is uninstalling/reinstalling. The thing is, I do not use NSUserDefaults, I use SwiftKeychainWrapper.
I need to clear that user's keychain when app uninstalls.
didFinishLaunchingWithOptions seems to call when app loads so no use there. Is there a way to detect a reinstall? I need to call this:
return KeychainWrapper.standard.removeObject(forKey: "myKey") // only when/if app is unsinstalled/reinstalling
Presumably you're using Keychain because you need to store sensitive information? If so then you could just store a boolean in UserDefaults and check if that exists. For example:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let freshInstall = !UserDefaults.standard.bool(forKey: "alreadyInstalled")
if freshInstall {
// delete your item from keychain
UserDefaults.standard.set(true, forKey: "alreadyInstalled")
}
return true
}
This way you still have the security of the Keychain, but the behaviour of UserDefaults on uninstall/reinstall.
for others searching for the way to clear the Keychain in the "// delete your item" part of the answer.....
Swift 3
let _ = KeychainWrapper.standard.removeAllKeys()

Parse Register for Push Notification - Crash if user not signed in

So i have push notifications setup and as part of the did register for push notifications i need to add the current user to the installation table. This works fine up untill there is no user signed in.
This is my code
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let types:UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]
let settings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let installation = PFInstallation.currentInstallation()
installation.setObject(PFUser.currentUser()!, forKey: "user")
installation.setDeviceTokenFromData(deviceToken)
installation.saveInBackground()
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
if error.code == 3010 {
print("Push notifications are not supported in the iOS Simulator.")
} else {
print("application:didFailToRegisterForRemoteNotificationsWithError: %#", error)
}
}
I need a way of registering the user with the installation table without it crashing if there is no user on, i would do a simple check to see if there is a user signed in and then run the code if there is a user, but then if someone sent a notification to them they wouldnt get it because their PFUser.currentUser() has not been added. Thanks in advance
Have you tried looking into Anonymous users (http://blog.parse.com/announcements/protect-user-data-with-new-parse-features/)? This allows you to create a PFUser for a logged out user.
This way, you can still save PFUser reference on the current installation via a PFUser.currentUser() call, but the user does not have to sign up.

CLLocationManager enabled but checked Never

I am trying to determine in AppDelegate if user set location permissions for application to "Never". My app always crashing if not getting location.
my code in AppDelegate is:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//location
var manager = CLLocationManager()
if CLLocationManager.authorizationStatus() == .Restricted
|| .authorizationStatus() == .Denied {
manager.requestWhenInUseAuthorization()
manager.requestAlwaysAuthorization()
}
}
Can anyone help me to resolve this issue?
The best article about CoreLocation and requesting authorization is here: http://nshipster.com/core-location-in-ios-8/
A couple of points:
Only request authorization if the current status is .NotDetermined
If the current status is .Denied, then you can post an alert asking
the user to go into settings and turn on location services, but calling either of the request methods will do nothing.
Remember to put in a NSLocationUsageDescription in your plist! (I
forget this routinely.)