Search code examples
iosswiftuiactivityviewcontroller

using the activityController to share label


I have the following code

 let textToShare = "Check out the test original for \(String(describing: bookTitle.text))"

        if let myWebsite = URL(string: "X") {//Enter link to your app here
            let objectsToShare = [textToShare, myWebsite] as [Any]
            let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)

            //Excluded Activities
            activityVC.excludedActivityTypes = [UIActivity.ActivityType.airDrop, UIActivity.ActivityType.addToReadingList]

            activityVC.popoverPresentationController?.sourceView = sender
            self.present(activityVC, animated: true, completion: nil)
        }

When i try to share the label text bookTitle.text, I get the output Optional("Test"). Is there a way to share UILabel text using the UIActivityViewController?


Solution

  • I get the output Optional("Test")

    Actually, you're in the right way. Except you need to "unwrap" that optional property .text. You can do it in so many ways. One way is to force unwrap it (not recommended most of the time!) Like so:

    let textToShare = "Check out the test original for \(bookTitle.text!)"
    

    Or one more way is to use nil coalescing. Like so:

    let textToShare = "Check out the test original for \(bookTitle.text ?? "")"
    

    More about Optional Chaining https://docs.swift.org/swift-book/LanguageGuide/OptionalChaining.html

    P.S no need to use String(describing:). You use it usually in print().