Can't share a png. or jpeg. file to messages app with sharelink

67 Views Asked by At

If I run this code in swiftUI in Xcode:

ShareLink(item: "Hi", preview: SharePreview("Hi"))

I get two apps in the simulator: Messages and Reminders.

However, if I run this code to share a png or jpeg file:

let theImage = Image("kort")

//The rest of my code[...]

ShareLink(item: theImage, preview: SharePreview("This is a image", image: theImage))

It just brings up the Reminders app in the Xcode simulator.

I need to write the code so I can share a photo via the messanger app. Can someone help?

1

There are 1 best solutions below

1
On

shareLink, you need to pass UUIImage

import SwiftUI

struct ContentView: View {
    var body: some View {
        if let uiImage = UIImage(named: "kort") {
            ShareLink(item: uiImage, preview: SharePreview("This is an image", image: Image(uiImage: uiImage)))
        } else {
            Text("Image not found")
        }
    }
}

the alternative is to use UIActivityViewController

import SwiftUI
import UIKit

struct ContentView: View {
    let image: UIImage // your image
    
    var body: some View {
        Button("Share Image") {
            shareImage()
        }
    }
    
    func shareImage() {
        let shareImage = UIActivityViewController(activityItems: [image], applicationActivities: nil)
        
        if let viewController = UIApplication.shared.windows.first?.rootViewController {
            viewController.present(shareImage, animated: true, completion: nil)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(image: UIImage(named: "kort")!) 
    }
}