cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 
Announcements
Back again with another edition of 'How we use Dropbox', so find out how Ross uses Dropbox to answer some new house questions here!

Dropbox API Support & Feedback

Find help with the Dropbox API from other developers.

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Short-lived token migration in Swift producing nil Client

Short-lived token migration in Swift producing nil Client

Jon B.1
Helpful | Level 6

I'm migrating an old Swift app to SwiftyDropbox 6.0.3 and short-lived tokens with refresh; our app needs offline access.  But with the code changes, I'm getting odd behaviour -- the completion handler in DropboxClientsManager.handleRedirectURL is never being called, with either a success or an error.  It just quietly fails and DropboxClientsManager.authorizedClient remains nil.

 

Here's my code fragment, which is basically the old sample code.  First, I've set the event handler:

 

            NSAppleEventManager.shared().setEventHandler(self,

                                                         andSelector: #selector(handleGetURLEvent),

                                                         forEventClass: AEEventClass(kInternetEventClass),

                                                         andEventID: AEEventID(kAEGetURL))

 

Then, there's the function which now calls authorizeFromControllerV2:

 

    func launchAuthorizeURL() {

        let scopeRequest = ScopeRequest(scopeType: .user, scopes: [], includeGrantedScopes: true)

        DropboxClientsManager.authorizeFromControllerV2(

            sharedWorkspace: NSWorkspace.shared,

            controller: viewController,

            loadingStatusDelegate: nil,

            openURL: { (url: URL) -> Void in

              NSLog("DbXConnect opening Dropbox URL")

              NSWorkspace.shared.open(url)

            },

            scopeRequest: scopeRequest // I've also tried with a nil scopeRequest

        )

    }

 

And the receiving end:

 

    @objc func handleGetURLEvent(_ event: NSAppleEventDescriptor?, replyEvent: NSAppleEventDescriptor?) {

        if let aeEventDescriptor = event?.paramDescriptor(forKeyword: AEKeyword(keyDirectObject)) {

            if let urlStr = aeEventDescriptor.stringValue {

                // It gets here...

                let url = URL(string: urlStr)!

                let oauthCompletion: DropboxOAuthCompletion = {

                    print("HandleGetURLEvent redirect completion handler running")   // It doesn't get here!

                  if let authResult = $0 {

                    switch authResult {

                    case .success (let newToken):

                        print("handleGetURLEvent: Success! User is logged into Dropbox.")

                        /* here I do my own setup */

                        // Launch confirmation page separately

                        NSWorkspace.shared.open(URL(string: "https://mysite/response.html")!)

                    case .cancel:

                        print("handleGetURLEvent: Authorization flow was manually canceled by user!")

                    case .error(let errCode, let description):

                        print("HandleGetURLEvent Error: \(description)")

                    }

                  }

                }

                let bResult = DropboxClientsManager.handleRedirectURL(url, completion: oauthCompletion)

                // this brings your application back to the foreground on redirect

                NSApp.activate(ignoringOtherApps: true)

            }

        }

        client = DropboxClientsManager.authorizedClient

        if (client == nil) {

            // It reports an error here.

        }

    }

 

This code worked fine with the old authorizeFromController call (and still does if I switch back that one call).

 

On a related note -- what's the best practice for how to specify offline token access with SwiftyDropbox?  Is that made available by default with authorizeFromControllerV2?

1 Accepted Solution

Accepted Solutions

Re: Short-lived token migration in Swift producing nil Client

Jon B.1
Helpful | Level 6

I think I've resolved it -- I'm still not sure why it was interfering with that URL scheme in the main program, but that may be down to the Group Container settings which lump the app and the Finder Sync extension together for communication purposes!

 

The source of the problem was that the Finder Sync extension was trying to connect to the socket on *its* main thread, and taking a full minute to fail.  By moving the connection attempt off of the main DispatchQueue onto a low-priority one, the problem with Dropbox not being able to get through to the main program vanished.

 

Strange, but hey, if it works...!

View solution in original post

8 Replies 8

Re: Short-lived token migration in Swift producing nil Client

Greg-DB
Dropboxer

I just gave this a try by setting up a new macOS project with your code snippets here, and it worked successfully for me. It got to "handleGetURLEvent: Success! User is logged into Dropbox.".

 

Can you let me know what versions of Xcode and macOS you're using? Also, what method did you use to install the SwiftyDropbox library?

 

The authorizeFromControllerV2 method automatically requests "offline" access.

Re: Short-lived token migration in Swift producing nil Client

Jon B.1
Helpful | Level 6

Update on this:  turns out the completion handler *was* running consistently, it just took about two minutes to do so, and so other things were timing out as a result!  It looks like something is sitting on the main thread in my app, which was blocking the completion handler from running.  I'm still investigating.

 

 

Basically, there were more changes than I thought between my old SwiftyDropbox version and 6.0.3.  Rather than having the logic continue in the original thread, I've now refactored so that the code which checks the client status and proceeds to my own completion handler is only executed at the end of the handleRedirectURL completion handler.

 

But even after these changes, it's still taking about 45 seconds for the handleRedirectURL completion handler to run.  Is there anything I need to know about how 6.0.3 deals with the main queue, which could explain the blocking?  Or is this a problem with the rest of my app?

Re: Short-lived token migration in Swift producing nil Client

Greg-DB
Dropboxer

Thanks for following up. I'm not aware of anything with the SwiftyDropbox SDK itself that would cause that. In my test, for instance, the entire completion handler runs pretty much instantaneously.

Re: Short-lived token migration in Swift producing nil Client

Jon B.1
Helpful | Level 6

Following from my previous update -- this is SwiftyDropbox 6.0.3 installed using CocoaPods, and Xcode 12.5 on Big Sur 11.4.  But as I said, I'm now suspecting that there's something going on elsewhere in my app, blocking the dispatch queue which authorizeFromControllerV2 / handleRedirectURL is trying to use.  Are there guidelines about what parts of the auth process should or shouldn't be called on the main thread?

Re: Short-lived token migration in Swift producing nil Client

Greg-DB
Dropboxer

I don't believe there's any specific guidance with respect to threading for the authorization process. The official documentation for implementing the app authorization flow can be found here.

Re: Short-lived token migration in Swift producing nil Client

Jon B.1
Helpful | Level 6

Here's a bit more on this.  The problem seems to be a timeout that's causing the application to sit for up to one minute between me pressing "Allow Safari to open [my app]" after pressing the Allow button during the auth process, and the event actually being received in my code.

 

As far as I can tell, there doesn't appear to be anything else running in my app at all during that time, it's completely idling.  But here's the weird bit -- my app has a FinderSync extension, as part of the same app group, which is trying to connect to the main application through a socket.  (It's not succeeding, because my app doesn't start listening until after the Dropbox connection is in place.)  But it keeps retrying for a minute before closing the socket...  and after it closes, suddenly the response comes through from Safari to my handleGetURLEvent method.

 

Note that none of this happened with the old SwiftyDropbox 3/4 version!  So I guess the next question is, how are the auth pages trying to send the message back to the main application, so that the kAEGetURL event is getting held up by either the app or the FinderSync handler in the same app group?...

Re: Short-lived token migration in Swift producing nil Client

Greg-DB
Dropboxer

The app authorization page in the browser connects back to the native app using a custom URL scheme, which the app sets in its plist file, from this step in the setup documentation. Specifically, it's the "db-<APP_KEY>" set in CFBundleURLSchemes under CFBundleURLTypes. (The Dropbox web page knows to redirect back to a URL using that URL scheme, which opens the app.)

 

I'm not familiar with Finder Sync extensions, but is there any reason it might be interfering with that URL scheme?

Re: Short-lived token migration in Swift producing nil Client

Jon B.1
Helpful | Level 6

I think I've resolved it -- I'm still not sure why it was interfering with that URL scheme in the main program, but that may be down to the Group Container settings which lump the app and the Finder Sync extension together for communication purposes!

 

The source of the problem was that the Finder Sync extension was trying to connect to the socket on *its* main thread, and taking a full minute to fail.  By moving the connection attempt off of the main DispatchQueue onto a low-priority one, the problem with Dropbox not being able to get through to the main program vanished.

 

Strange, but hey, if it works...!

View solution in original post

Who's talking

Top contributors to this post

  • User avatar
    Jon B.1 Helpful | Level 6
  • User avatar
    Greg-DB Dropboxer
What do Dropbox user levels mean?
Need more support?