Search code examples
swiftxcodeuiactivityviewcontrollercancellationuiactivity

UIActivityViewController handle Cancel action | Swift/Xcode


I can't find complete code in Swift of how to execute an action when the user presses the "x" in a UIActivityViewController (top right), cancelling the share.

This is what I currently have:

do {
                try pdfData.write(to: temporaryFileURL)
                let vc = UIActivityViewController(activityItems: [temporaryFileURL], applicationActivities: [])
                self.present(vc, animated: true, completion: nil)
            } catch {
                print(error)
            }

I found this Objective-C code that may work. Can someone convert it to Swift for me and show me how I could implement it with what I currently have?

vc.completionWithItemsHandler = ^(NSString *activityType,
                                                          BOOL completed,
                                                          NSArray *returnedItems,
                                                          NSError *error){
                    // react to the completion
                    if (completed) {
                        
                        // user shared an item
                        NSLog(@"We used activity type%@", activityType);
                        
                    } else {
                        
                        // user cancelled
                        NSLog(@"We didn't want to share anything after all.");
                    }
                    
                    if (error) {
                        NSLog(@"An Error occured: %@, %@", error.localizedDescription, error.localizedFailureReason);
                    }
                };

Thank you!


Solution

  • You can do it this way.

    vc.completionWithItemsHandler = { activityType, completed, returnedItems, 
    error in
        // Your logic here
    }