Use of unresolved identifier 'url' - swift

I'm completely new to API's, and am following this tutorial on appcoda
https://www.appcoda.com/dropbox-api-tutorial/
It's been going very smoothly, but I've run into a problem, and given that I'm a novice, I don't have the first clue with how to fix it.
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let appKey = "n00nzv68gtxk6c9" // Set your own app key value here.
let appSecret = "itumv0icksr7yj6" // Set your own app secret value here.
let dropboxSession = DBSession(appKey: appKey, appSecret: appSecret, root: kDBRootDropbox)
DBSession.setShared(dropboxSession)
return true
if DBSession.sharedSession().handleOpenURL(url) {
if DBSession.shared().isLinked() {
NotificationCenter.defaultCenter.postNotificationName("didLinkToDropboxAccountNotification", object: nil)
return true
}
}
return false
}
The problem is in the line
if DBSession.sharedSession().handleOpenURL(url) {
where I get the error
Use of unresolved identifier 'url'
What do I need to do?

Per the tutorial, you need to use the correct delegate method within AppDelegate.swift
// handle custom application schemes
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
if DBSession.sharedSession().handleOpenURL(url) {
print("Url defined as \( url)")
}
}

Related

Failed to get FirebaseApp instance even though I used FirebaseApp.configure()

I'm trying to use firebase firestore but keep getting this error:
Thread 1: "Failed to get FirebaseApp instance. Please call FirebaseApp.configure() before using Firestore"
This happens even though I do call FirebaseApp.configure() here:
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
FirebaseApp.configure()
return true
}
}
And I have been using firebase authentication with no problems. Anyone know how to fix this?

AppTransparencyTracking not working in Swift UI

Since SwiftUI doesnt have a Appdelegate file, I tried adding it through App.swift file.
However, it still doesnt work. What am i missing ?
imported the libraries
import AppTrackingTransparency
import AdSupport
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {func requestIDFA() {
ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in
// Tracking authorization completed. Start loading ads here.
// loadAd()
})
}
Then called the appdelegate under #main
#main
struct MyApp: App {
#UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
If you look at the didFinishLaunchingWithOptions function. You have a call function inside another function so the requestIDFA never calls.
Put your requestIDFA() function out side the didFinishLaunchingWithOptions and call inside the didFinishLaunchingWithOptions.
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
requestIDFA()
return true
}
func requestIDFA() {
ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in
// Tracking authorization completed. Start loading ads here.
// loadAd()
})
}
}
Note: Make sure you have an added key to your Info.plist.
<key>NSUserTrackingUsageDescription</key>
<string>Your reason, why you want to track the user</string>

SwiftUI swizzling disabled by default, phone auth not working

I am building a screen with phone number login. I checked over and over again and the project is newly created, however, I am getting this log:
7.2.0 - [Firebase/Auth][I-AUT000015] The UIApplicationDelegate must handle remote notification for phone number authentication to work.
If app delegate swizzling is disabled, remote notifications received by UIApplicationDelegate need to be forwarded to FIRAuth's canHandleNotificaton: method.
I did read in the documentation about swizzling and I don't know why it seems to be disabled, I did not disabled it. I have added GoogleServices-Info.plist into the app, I added in firebase panel the app apn auth key.
My entry point in the app looks like this:
#main
struct partidulverdeApp: App {
init() {
FirebaseApp.configure()
}
var body: some Scene {
WindowGroup {
MainView()
.onOpenURL { url in
Auth.auth().canHandle(url.absoluteURL)
}
}
}
}
My URL Types property has an entry with the RESERVED_CLIENT_ID
I am very desperate about this problem. Any idea is highly appreciated.
Edit1:
I did read the documentation and tried to handle notification with swizzling disabled, but I get the same error:
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication,
didReceiveRemoteNotification notification: [AnyHashable : Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
if Auth.auth().canHandleNotification(notification) {
completionHandler(.noData)
return
}
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
print("Your code here")
return true
}
}
#main
struct partidulverdeApp: App {
#UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
init() {
FirebaseApp.configure()
}
var body: some Scene {
WindowGroup {
MainView()
.onOpenURL { url in
Auth.auth().canHandle(url.absoluteURL)
}
}
}
}
Here's how to implement Phone Number Auth using the new SwiftUI 2 life cycle:
Create a Firebase project and set up PhoneNumber Auth
Add your iOS app to the Firebase project, download and add GoogleService-Info.plist to your project
In Xcode, select the application target and enable the following capabilities:
Push notifications
Background modes > Remote notifications
Create and register an APNS authentication key on the Apple developer portal
Upload the key to Firebase (under Project Settings > Cloud messaging in the Firebase Console)
Add the Firebase project's reversed client ID to your app's URL schemes
In your Info.plist, set FirebaseAppDelegateProxyEnabled to NO
Implement the AppDelegate as follows:
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
FirebaseApp.configure()
print("SwiftUI_2_Lifecycle_PhoneNumber_AuthApp application is starting up. ApplicationDelegate didFinishLaunchingWithOptions.")
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("\(#function)")
Auth.auth().setAPNSToken(deviceToken, type: .sandbox)
}
func application(_ application: UIApplication, didReceiveRemoteNotification notification: [AnyHashable : Any], fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
print("\(#function)")
if Auth.auth().canHandleNotification(notification) {
completionHandler(.noData)
return
}
}
func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool {
print("\(#function)")
if Auth.auth().canHandle(url) {
return true
}
return false
}
}
#main
struct SwiftUI_2_Lifecycle_PhoneNumber_AuthApp: App {
#UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
var body: some Scene {
WindowGroup {
ContentView()
.onOpenURL { url in
print("Received URL: \(url)")
Auth.auth().canHandle(url) // <- just for information purposes
}
}
}
}
For further reading, I suggest these two articles I wrote:
Firebase and the new SwiftUI 2 Application Life Cycle
The Ultimate Guide to the SwiftUI 2 Application Life Cycle

Can I expose a Swift function to React Native without using Objective-C (pure swift)?

I wonder if I can expose my func navigateToLoginWidget to React Native. So that it can be triggered from RN.
I have managed to change the Objective-C template that comes with React Native to Swift like so:
import Foundation
import IBMCloudAppID
import BMSCore
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var bridge: RCTBridge!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// initializing App ID SDK
let region = AppID.REGION_SOMEWHERE
let backendGUID = "MY_TENANT_ID_FROM_IBM"
AppID.sharedInstance.initialize(tenantId: backendGUID, region: region)
// Initializing React Native front-end with Swift instead of Obj-c template
let jsCodeLocation: URL
jsCodeLocation = RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index.js", fallbackResource:nil)
let rootView = RCTRootView(bundleURL: jsCodeLocation, moduleName: "MY_PROJECT_NAME", initialProperties: nil, launchOptions: launchOptions)
let rootViewController = UIViewController()
rootViewController.view = rootView
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = rootViewController
self.window?.makeKeyAndVisible()
return true
}
func application(_ application: UIApplication, open url: URL, options :[UIApplication.OpenURLOptionsKey : Any]) -> Bool {
return AppID.sharedInstance.application(application, open: url, options: options)
}
func navigateToLoginWidget(_ sender : Any) {
print("clicked")
AppID.sharedInstance.loginWidget?.launch(delegate: SigninDelegate)
}
}
I would normally have this function in another module called SigninDelegate.swift, but I have included it in the same class for explanatory purposes.
According to the official documentation:
Swift doesn't have support for macros so exposing it to React Native
requires a bit more setup but works relatively the same.
So yes, it is possible, but some setup is needed. Check the docs in the link above for the steps you need to follow to set it up.

Parse Push Notifications - Swift Installation Not Working

I am trying to get Parse push notifications working on my app (all swift) but while trying to implement, I get the error 'PFInstallation' does not have a member named 'saveInBackground'
Here is my code.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Parse.setApplicationId("APP ID HIDDEN", clientKey: "CLIENT ID HIDDEN")
// let notificationTypes:UIUserNotificationType = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
//let notificationSettings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
var notificationType: UIUserNotificationType = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
var settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationType, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
//UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
// Override point for customization after application launch.
return true
}
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings!) {
UIApplication.sharedApplication().registerForRemoteNotifications()
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
var currentInstallation: PFInstallation = PFInstallation()
currentInstallation.setDeviceTokenFromData(deviceToken)
currentInstallation.saveInBackground()
println("got device id! \(deviceToken)")
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
println(error.localizedDescription)
println("could not register: \(error)")
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
}
When I change the currentInstallation.saveInBackground to currentInstallation.saveEvenutally() , the code compiles fine..
But when trying to successfully sign up for push notifications, an error pops up in the console saying Error: deviceType must be specified in this operation (Code: 135, Version: 1.4.2)
I have spent hours trying to figure this out, no dice, any help is appreciate.
To anyone else who has this error, make sure you import the Bolts framework into your Bridging Header file
Which isn't outlined in their crap docs.
That fixes the issue.
Below is the code.
#import <Parse/Parse.h>
#import <Bolts/Bolts.h>
Just add that to your bridging header then you are good to go. Thanks
A valid PFInstallation can only be instantiated via [PFInstallation currentInstallation] because the required identifier fields are readonly. (source)
So instead of:
var currentInstallation: PFInstallation = PFInstallation()
Try:
var currentInstallation = PFInstallation.currentInstallation()
Just write import Bolts in you AppDelegate.swift file
In addition to importing Bolts, I fixed the same error in my app by changing the function to
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
// Store the deviceToken in the current Installation and save it to Parse
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.saveInBackground()
}
From the Parse guide on Push Notifications (as opposed to quickstart guide): https://parse.com/docs/ios/guide#push-notifications