2

I am trying to share a formatted version of an array of structs.

if #available(iOS 16.0, *) {
    ShareLink(item: observedObject.toFormattedString())
} else {
    // Fallback on earlier versions
}

However, I get a Thread 1: EXC_BAD_ACCESS (code=1, address=0xab849c4e0c41cdb0) when launching the app and the array (stored with @AppStorage) isn't empty.

format function

Is there a way to accomplish the equivalent of passing a function to ShareLink that only gets called when the Share button is pressed?

ShareLink(item: {
   observedObject.toFormattedString()
})

I tried this code but nothing happens. (edit: it works if the sheet isn't in a toolbar)

Edit: The issue is with String(format: "%s %s %s", a, b, c), there are no crashes if I use "\(a) \(b) \(c)".

BPDev
  • 397
  • 1
  • 9

1 Answers1

0

Combining this video and this answer:

Button {
    share(text: "Test")
} label: {
    Label("Share", systemImage: "square.and.arrow.up")
}
func share(text: String){
    let viewController = UIActivityViewController(activityItems: [text], applicationActivities: nil)

    let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene
    let window = windowScene?.windows.first
    
    window?.rootViewController?.present(viewController, animated: true)
    
    if UIDevice.current.userInterfaceIdiom == .pad {
        viewController.popoverPresentationController?.sourceView = window
        viewController.popoverPresentationController?.sourceRect = CGRect(x: UIScreen.main.bounds.width / 2.1 , y: UIScreen.main.bounds.height / 1.3, width: 200, height: 200)
    }
}

I think that the iPad crashes because it doesn't know where to place the share box. There must be a better way to position it.

BPDev
  • 397
  • 1
  • 9