FBSDKLoginManager logInWithReadPermissions:fromViewController:handler:]: unrecognized selector sent to instance 0x7fed38d61290 - facebook

I can't seem to resolve this issue. I went in and deleted all parse and fb SDKs and then downloaded the newest parse and fb SDKs and put into project.
Still getting this error in logs. Don't even get to fb screen. Below is my code. I have researched all instances of this issue and yet no resolve. I am missing something.
AppDelegate.swift:
import UIKit
import Parse
import ParseFacebookUtilsV4
import Bolts
// If you want to use any of the UI components, uncomment this line
// import ParseUI
// If you want to use Crash Reporting - uncomment this line
// import ParseCrashReporting
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
//--------------------------------------
// MARK: - UIApplicationDelegate
//--------------------------------------
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Enable storing and querying data from Local Datastore.
// Remove this line if you don't want to use Local Datastore features or want to use cachePolicy.
Parse.enableLocalDatastore()
let parseConfiguration = ParseClientConfiguration(block: { (ParseMutableClientConfiguration) -> Void in
ParseMutableClientConfiguration.applicationId = "xxx"
ParseMutableClientConfiguration.clientKey = "xxx"
ParseMutableClientConfiguration.server = "https://yourapp.herokuapp.com/parse"
})
Parse.initializeWithConfiguration(parseConfiguration)
PFFacebookUtils.initializeFacebookWithApplicationLaunchOptions(launchOptions)
PFUser.enableAutomaticUser()
let defaultACL = PFACL();
// If you would like all objects to be private by default, remove this line.
defaultACL.publicReadAccess = true
PFACL.setDefaultACL(defaultACL, withAccessForCurrentUser:true)
if application.applicationState != UIApplicationState.Background {
// Track an app open here if we launch with a push, unless
// "content_available" was used to trigger a background push (introduced in iOS 7).
// In that case, we skip tracking here to avoid double counting the app-open.
let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus")
let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:")
var noPushPayload = false;
if let options = launchOptions {
noPushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil;
}
if (preBackgroundPush || oldPushHandlerOnly || noPushPayload) {
PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
}
}
if application.respondsToSelector("registerUserNotificationSettings:") {
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
} else {
let types: UIRemoteNotificationType = [UIRemoteNotificationType.Badge, UIRemoteNotificationType.Alert, UIRemoteNotificationType.Sound]
application.registerForRemoteNotificationTypes(types)
}
return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}
//--------------------------------------
// MARK: Push Notifications
//--------------------------------------
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.saveInBackground()
PFPush.subscribeToChannelInBackground("") { (succeeded, error) in
if succeeded {
print("ParseStarterProject successfully subscribed to push notifications on the broadcast channel.");
} else {
print("ParseStarterProject failed to subscribe to push notifications on the broadcast channel with error = %#.", error)
}
}
}
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)
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
if application.applicationState == UIApplicationState.Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
}
}
func application(application: UIApplication,
openURL url: NSURL,
sourceApplication: String?,
annotation: AnyObject) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
}
func applicationDidBecomeActive(application: UIApplication) {
FBSDKAppEvents.activateApp()
}
}
ViewController.swift:
import UIKit
import Parse
import FBSDKCoreKit
import FBSDKLoginKit
import ParseFacebookUtilsV4
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// array of what we want to get from the fb user account
let permissions = ["public_profile"]
PFFacebookUtils.logInInBackgroundWithReadPermissions(permissions) {
(user: PFUser?, error: NSError?) -> Void in
if let error = error { // if error exists
print(error)
} else {
if let user = user { // if user exists
print(user)
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Related

Google login user profile not updated to Firebase

I am new to Xcode and I am working on my Google sign-in project. After successfully logging in with google, I cannot find the user profile in firebase. I think I am missing the code for uploading user credentials to firebase. I can barely understand the documentation and I don't know what to do. By the way, how can I navigate to another view controller after signing in? I tried lots of ways but none of them work. Any help is appreciated.
My AppDelegate code:
import UIKit
import Firebase
import GoogleSignIn
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate{
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
GIDSignIn.sharedInstance()?.clientID = "//I have it in my actual code"
GIDSignIn.sharedInstance()?.delegate = self
return true
}
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if let error = error {
print(error)
return
}
guard
let authentication = user?.authentication,
let idToken = authentication.idToken
else {
return
}
let credential = GoogleAuthProvider.credential(withIDToken: idToken,
accessToken: authentication.accessToken)
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
return GIDSignIn.sharedInstance().handle(url)
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
The code of the log-in view controller
import UIKit
import GoogleSignIn
class WelcomeViewController: UIViewController {
#IBOutlet weak var gooleButton: GIDSignInButton!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
GIDSignIn.sharedInstance()?.presentingViewController = self
gooleButton.style = .wide
gooleButton.colorScheme = .dark
}
}
From what I see your code signs the user in with Google to get the credentials, but then doesn't call signIn(with: ) which is needed in order to sign in to Firebase Authentication.
Have a look at Step 3: authenticate with Firebase. While the code there looks a bit intimidating, that's mostly because it handled many different cases. At its minimum you can sign in to Firebase with your credentials by doing:
Auth.auth().signIn(with: credential) { authResult, error in
if let error = error {
let authError = error as NSError
print(error.localizedDescription)
return
}
// User is signed in
// ...
}

Unable to navigate to other view controller after Google sign-in

How can I go to another view controller after successfully signing with google? I've tried "self.inputViewController?.performSegue(withIdentifier: "goToMain", sender: self)" in my App Delegate but not getting any respond. Am I supposed to add the method in App Delegate or the view controller with the sign-in button?
App Delegate
import UIKit
import Firebase
import GoogleSignIn
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate{
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
GIDSignIn.sharedInstance()?.clientID = "my_client_id"
GIDSignIn.sharedInstance()?.delegate = self
return true
}
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if let error = error {
print(error)
return
}
guard
let authentication = user?.authentication,
let idToken = authentication.idToken
else {
return
}
let credential = GoogleAuthProvider.credential(withIDToken: idToken,
accessToken: authentication.accessToken)
Auth.auth().signIn(with: credential) { authResult, error in
if let error = error {
let authError = error as NSError
print(authError.localizedDescription)
return
}
self.inputViewController?.performSegue(withIdentifier: "goToMain", sender: self)
}
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
return GIDSignIn.sharedInstance().handle(url)
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
Are you sure about the inputViewController is not nil? This may a reason for not working.
You can add a function to test this, or you can use the print function to check, or, you can use debug point to check inputViewController is nil or not.
I'd like to add comment but I don't have enough reputation point :).
Good luck.

Why the push notification don‘t work in iOS with Firebase from device to device?

I have created the Production Identifier and all this stuff and it has worked but sometime later suddenly it doesn't work anymore. And I have nothing changed in the Notification Area in my code.
From Firebase Cloud Messaging - Test Sending works fine. But from Device to Device not.
import UIKit
import Firebase
import FirebaseMessaging
import FirebaseInstanceID
import UserNotifications
import AVFoundation
import GoogleMobileAds
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
static let NOTIFICATION_KEY = "https://gcm-http.googleapis.com/gcm/send"
static var DEVICE_ID = String()
static let SERVER_KEY = "AAAACucgXz8:APA91bE_vEyKiqR34sruY2f5tetjj_DrwVi42v9tL015tLEOZmwBh-q7oWsNXUrpR0S9XBCrbxMJtgUu70xNAyDeouNvxn1kHKll2Dcwzxbf40lbappxs-o6IDvHVvEajzX5Dzsq8MW8"
static var EXITAPP = Bool()
static var LIKESCOUNTER = Int()
var dateForm = DateFormatter()
var timeFormatter = DateFormatter()
static var INSERTTIME = false
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible() //Damit wir die ganzen Views selber bearbeiten können.
window?.rootViewController = UINavigationController(rootViewController: ViewController())
if #available(iOS 10.0, *){
UNUserNotificationCenter.current().delegate = self
let option: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: option) { (bool, err) in
}
}
application.registerForRemoteNotifications()
UIApplication.shared.applicationIconBadgeNumber = 0
GADRewardBasedVideoAd.sharedInstance().load(GADRequest(), withAdUnitID: "ca-app-pub-3940256099942544/1712485313")
if #available(iOS 9.0, *){
application.isStatusBarHidden = true //HIDE STATUS BAR
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
insertOnlineActivity(online: false)
connectToFCM()
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
AppDelegate.EXITAPP = true
// if AppDelegate.INSERTTIME{
// insertLastLikedTime()
// }
insertOnlineActivity(online: false)
connectToFCM()
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
insertOnlineActivity(online: true)
connectToFCM()
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
insertOnlineActivity(online: true)
connectToFCM()
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String){
guard let newToken = InstanceID.instanceID().token() else {return}
AppDelegate.DEVICE_ID = newToken
connectToFCM()
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
let notification = response.notification.request.content.body
print(notification)
completionHandler()
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
guard let newToken = InstanceID.instanceID().token() else {return}
//let newToken = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
AppDelegate.DEVICE_ID = newToken
connectToFCM()
Messaging.messaging().setAPNSToken(deviceToken, type: .unknown)
}
func connectToFCM(){
Messaging.messaging().shouldEstablishDirectChannel = true
}
This is how I call the Notification
fileprivate func setUpPushNotifications(fromDeviceID: String){
let message = self.userName + " has sent you a voice message."
let title = "New Message"
let toDeviceID = fromDeviceID
var headers:HTTPHeaders = HTTPHeaders()
headers = ["Content-Type":"application/json","Authorization":"key=\(AppDelegate.SERVER_KEY)"]
let notifications = ["to" : "\(toDeviceID)" , "notification":["body":message,"title":title,"badge":1,"sound":"default"]] as [String : Any]
request(AppDelegate.NOTIFICATION_KEY as URLConvertible, method: .post as HTTPMethod, parameters: notifications, encoding: JSONEncoding.default, headers: headers).response { (response) in
print(response)
}
}

How to ask for remote permission in iOS 10/Swift 3

I want to ask the user for permissions (remote and local notifications, camera and audio) from a separate viewController. The viewcontroller will be presented during the onboarding process, and never again.
How can I ask for permissions to display remote notifications outside the AppDelegate?
My question is not how to trigger them, but how to make sure that the AppDelegate is "responsible" for handling them once a permission have been granted.
Current code in AppDelegate
import UIKit
import UserNotifications
import PushKit
import CallKit
AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, UNUserNotificationCenterDelegate {
let pushRegistry = PKPushRegistry(queue: DispatchQueue.main)
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
pushRegistry.delegate = self
pushRegistry.desiredPushTypes = [.voIP]
....
}
ViewController where I ask for permission
import UIKit
import UserNotifications
class AskForNotificationPermissionVC: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
requestPermissions { (videoGranted, audioGranted, notificationsGranted) in
if videoGranted && audioGranted && notificationsGranted {
DispatchQueue.main.async{
self.performSegue(withIdentifier: "toPaySegue", sender: self)
}
} else {
DispatchQueue.main.async{
self.presentSpecialPopoup()
}
}
}
}
func requestPermissions (completion: #escaping ((Bool, Bool, Bool)->())) {
let center = UNUserNotificationCenter.current()
center.delegate = UIApplication.shared.delegate as! UNUserNotificationCenterDelegate?
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (videoGranted: Bool) -> Void in
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeAudio, completionHandler: { (audioGranted: Bool) -> Void in
center.requestAuthorization(options: [.alert, .badge, .sound]) { (notificationGranted:Bool, error) -> Void in
UIApplication.shared.registerForRemoteNotifications()
completion(videoGranted, audioGranted, notificationGranted)
}
})
})
}
}
Any help is very, very much appreciated !! Thank you.
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
//handle result
}

Parse.com chek push notification before showing

How to check push notification before showing?
I want check data and if incorrect data I don't want show notification
my code:
I just use simple Parse.com example. This is my AppDelegate class
let defaults = NSUserDefaults.standardUserDefaults()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Parse.setApplicationId("//",
clientKey: "//")
if application.applicationState != UIApplicationState.Background {
let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus")
let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:")
var pushPayload = false
if let options = launchOptions {
pushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil
}
if (preBackgroundPush || oldPushHandlerOnly || pushPayload) {
PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
}
}
var notificationActionAccept :UIMutableUserNotificationAction = UIMutableUserNotificationAction()
notificationActionAccept.identifier = "FIRST_ACTION"
notificationActionAccept.title = "Įvertinti"
var notificationCategory:UIMutableUserNotificationCategory = UIMutableUserNotificationCategory()
notificationCategory.identifier = "CallNotificationCategory"
notificationCategory .setActions([notificationActionAccept], forContext: UIUserNotificationActionContext.Default)
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Sound, .Badge], categories: NSSet(array:[notificationCategory]) as! Set<UIUserNotificationCategory>)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
if let launchOptions = launchOptions as? [String : AnyObject] {
if let notificationDictionary = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] as? [NSObject : AnyObject] {
self.application(application, didReceiveRemoteNotification: notificationDictionary)
}
}
return
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool
{
return
}
func applicationWillResignActive(application: UIApplication) {
}
func applicationDidEnterBackground(application: UIApplication) {
}
func applicationWillEnterForeground(application: UIApplication) {
}
func applicationDidBecomeActive(application: UIApplication) {
}
func applicationWillTerminate(application: UIApplication) {
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let installation = PFInstallation.currentInstallation()
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)
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
print(userInfo)
PFPush.handlePush(userInfo)
if application.applicationState == UIApplicationState.Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
}
}
}
I Realy need help:/
No, unfortunately you can not stop notification from showing when your app is in background.
application:didReceiveRemoteNotification: is just a delegate method, which is invoked upon notification showing, it can not control if notification should be shown or not.