Search code examples
iphoneswiftsharecontactscncontact

Limit what opens appear while sharing contact


I want to share a contact inside of my application but I only want to let the user do it via Message and Mail. Can I block out all other options on the alert sheet?

func shareContacts(contacts: [CNContact]) throws {

        guard let directoryURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else {
            return
        }

        var filename = NSUUID().uuidString

        // Create a human friendly file name if sharing a single contact.
        if let contact = contacts.first, contacts.count == 1 {

            if let fullname = CNContactFormatter().string(from: contact) {
                filename = fullname.components(separatedBy:" ").joined(separator: "")
            }
        }

        let fileURL = directoryURL
            .appendingPathComponent(filename)
            .appendingPathExtension("vcf")

        let data = try CNContactVCardSerialization.data(with: contacts)

        try data.write(to:fileURL, options: [.atomicWrite])
         let textToShare = "This is my clear captions text test"
         let objectsToShare = [textToShare, fileURL] as [Any]
                let activityViewController = UIActivityViewController(
                    activityItems: objectsToShare,
                    applicationActivities: nil
                )

        present(activityViewController, animated: true, completion: {})
    }

Solution

  • It is not possible to simply exclude everything besides Mail and iMessage but you can do the following.

    You can use a function to exclude options for the UIActivityViewController but there are only some apps you can disable. To disable more you would need a private API and you would violate the App Guidelines Apple has for all iOS Apps.

    You are allowed to disable these types:

    UIActivityTypePostToFacebook, 
    UIActivityTypePostToTwitter, 
    UIActivityTypePostToWeibo, 
    UIActivityTypeMessage, 
    UIActivityTypeMail, 
    UIActivityTypePrint, 
    UIActivityTypeCopyToPasteboard, 
    UIActivityTypeAssignToContact,
    UIActivityTypeSaveToCameraRoll,
    UIActivityTypeAddToReadingList,
    UIActivityTypePostToFlickr,
    UIActivityTypePostToVimeo,
    UIActivityTypePostToTencentWeibo,
    UIActivityTypeAirDrop
    

    by using this code (Xcode suggests you the exact types):

    activityController.excludedActivityTypes = [
        UIActivityType.assignToContact,
    
        // ... and all of the types you want to disable
    
        // If you know the rawValue/BundleID of other types you can try to disable them too like this
        UIActivityType(rawValue: "..."),
    ]
    

    Apple Documentation about UIActivityViewController

    Check out this question: How to exclude Notes and Reminders apps from the UIActivityViewController?