4

For some time I have been trying to find a solution to authenticating Dropbox using their SwiftyDropbox SDK in a SwiftUI project, but this was to no avail.

The instructions provided in the readme use an AppDelegate and and SceneDelegate. The latter of which from what I understand is not possible with SwiftUI. I have been able to get the OAuth2 Safari window to launch, but DropboxClientsManager.authorizedClient is always nil.

2
  • 2
    To make this fit with the Stack Overflow format, you can create a question and then leave the solution as an answer, as opposed to putting the answer in the question itself and then leaving it unanswered.
    – jnpdx
    Commented Mar 18, 2022 at 17:54
  • Thank you @jnpdx for you suggestion. I will make the modification
    – Michael C
    Commented Mar 18, 2022 at 19:11

2 Answers 2

5

Finally, I figured it.

Setup info.plist as the SwiftyDropbox readme instructs.

// <app_name>.swift

import SwiftUI
import SwiftyDropbox

@main
struct DropboxTestApp: App {

    init() {
        DropboxClientsManager.setupWithAppKey("<app key>")
    }
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
// ContentView.swift

import SwiftUI
import SwiftyDropbox

struct ContentView: View {
    
    @State var isShown = false
    
    var body: some View {
        VStack {
            
            Button(action: {
                self.isShown.toggle()
            }) {
                Text("Login to Dropbox")
            }

            DropboxView(isShown: $isShown)
            
            Button {
                if let client = DropboxClientsManager.authorizedClient {
                    print("successful login")
                } else {
                    print("Error")
                }
            } label: {
                Text("Test Login")
            }
            
        }
        .onOpenURL { url in
            let oauthCompletion: DropboxOAuthCompletion = {
                if let authResult = $0 {
                    switch authResult {
                    case .success:
                        print("Success! User is logged into DropboxClientsManager.")
                    case .cancel:
                        print("Authorization flow was manually canceled by user!")
                    case .error(_, let description):
                        print("Error: \(String(describing: description))")
                    }
                }
            }
            DropboxClientsManager.handleRedirectURL(url, completion: oauthCompletion)
        }
    }
}

struct DropboxView: UIViewControllerRepresentable {
    typealias UIViewControllerType = UIViewController
    
    @Binding var isShown : Bool
    
    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
        
        if isShown {
            let scopeRequest = ScopeRequest(scopeType: .user, scopes: ["account_info.read", "files.metadata.write", "files.metadata.read", "files.content.write", "files.content.read"], includeGrantedScopes: false)
            DropboxClientsManager.authorizeFromControllerV2(
                UIApplication.shared,
                controller: uiViewController,
                loadingStatusDelegate: nil,
                openURL: { (url: URL) -> Void in UIApplication.shared.open(url, options: [:], completionHandler: nil) },
                scopeRequest: scopeRequest)
        }
    }
    
    func makeUIViewController(context _: Self.Context) -> UIViewController {
        return UIViewController()
    }
}

You don't need to create an AppDelegate.

I hope that someone may find this useful.

2
  • Doesn't work. This pattern of creating a UIViewController on demand and presenting from it doesn't always work. Commented Jan 3 at 14:48
  • It does work for me with XCode 15.3. However, the creation of the DropboxView, despite working nice, is not entirely need. I'll post in a second solution, but great thansk to @MichaelC for providing how to handle the URL.
    – Enric
    Commented Jun 13 at 18:30
0

This alternate solution does not require creating the DropboxView, although works exactly the same (opening the loging flow in a new window). For the call to DropboxClientsManager.setupWithAppKey I've added an AppDelegate instead to the SwiftUI project, and also brierfly tested adding it to .onChange(of: scenePhase) for the .active scenePhase and also seems to work.

struct ContentView: View {
    
    var body: some View {
        VStack {
            Spacer()

            Button("Login with Dropbox") {
                performLogin()
            }
            
            Spacer()
            Spacer()
        }
        .padding()
        .onOpenURL { url in
            print("url: \(url)")
            let oauthCompletion: DropboxOAuthCompletion = {
                if let authResult = $0 {
                    switch authResult {
                    case .success:
                        print("Success! User is logged into DropboxClientsManager.")
                    case .cancel:
                        print("Authorization flow was manually canceled by user!")
                    case .error(_, let description):
                        print("Error: \(String(describing: description))")
                    }
                }
            }
            DropboxClientsManager.handleRedirectURL(url, backgroundSessionIdentifier: "patata", completion: oauthCompletion)
        }
    }
    
    func performLogin() {
        let scopeRequest = ScopeRequest(scopeType: .user, scopes: ["account_info.read", "files.metadata.write", "files.metadata.read", "files.content.write", "files.content.read"], includeGrantedScopes: false)
        DropboxClientsManager.authorizeFromControllerV2(
            UIApplication.shared,
            controller: nil,
            loadingStatusDelegate: nil,
            openURL: { (url: URL) -> Void in UIApplication.shared.open(url, options: [:], completionHandler: nil) },
            scopeRequest: scopeRequest
        )
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.