ios - Share text and image both at the same time on social media apps like facebook, instagram, whatsapp and on linkedin - Stack

admin2025-04-16  6

I'm trying to share title and image as url on social media apps, but getting no success, I'm using the below code for the same, but only image is sharing text is not sending.. please let me know if i'm doing anything wrong here.. Thanks in advance!

import LinkPresentation

class ShareItem: NSObject, UIActivityItemSource {
    private let url: URL
    private let title: String

    var activityTitle: String? {
        return title
    }

    
    init(url: URL, title: String? = "") {
        self.url = url
        self.title = title ?? ""
    }

    func activityViewControllerPlaceholderItem(_: UIActivityViewController) -> Any {
        title
    }

    func activityViewController(_: UIActivityViewController, itemForActivityType _: UIActivity.ActivityType?) -> Any? {
        url
    }

    func activityViewController(_: UIActivityViewController, subjectForActivityType _: UIActivity.ActivityType?) -> String {
        title
    }

    func activityViewController(_: UIActivityViewController, dataTypeIdentifierForActivityType _: UIActivity.ActivityType?) -> String {
        (try? url.resourceValues(forKeys: [.typeIdentifierKey]).typeIdentifier) ?? ""
    }

    func activityViewController(_: UIActivityViewController, thumbnailImageForActivityType _: UIActivity.ActivityType?, suggestedSize _: CGSize) -> UIImage? {
        UIImage(contentsOfFile: url.absoluteString)
    }

    func activityViewControllerLinkMetadata(_: UIActivityViewController) -> LPLinkMetadata? {
        let metadata = LPLinkMetadata()
        
        // Set the title and other metadata
        metadata.title = title
        metadata.originalURL = url
        metadata.url = url
        metadata.iconProvider = NSItemProvider.init(contentsOf: url)
        // Ensure the image provider is valid
        if let image = UIImage(contentsOfFile: url.path) {
            metadata.imageProvider = NSItemProvider(object: image)
        }
        return metadata
    }
    
    
    static func saveImageForSharing(image: UIImage, completion: @escaping (URL?) -> Void) {
        let tempDirectory = FileManager.default.temporaryDirectory
        let fileName = UUID().uuidString + ".png"
        let fileURL = tempDirectory.appendingPathComponent(fileName)
        if let imageData = image.pngData() {
            do {
                try imageData.write(to: fileURL)
                completion(fileURL)
            } catch {
                print("Error saving image: \(error)")
                completion(nil)
            }
        } else {
            print("Error converting image to PNG data")
            completion(nil)
        }
    }
}
转载请注明原文地址:http://anycun.com/QandA/1744772067a87406.html