Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIActivityViewController in Swift Crashes on iPad

I am making a share function in my game and I have the code and it works fine on iPhone but when I test it on a iPad, when I tap the share button the app crashes. I am using the following code for the share button

let textToShare = "Check out this website!"

if let myWebsite = NSURL(string: "http://www.apple.com/") {
   let objectsToShare = [textToShare, myWebsite]
   let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
   self.view?.window?.rootViewController?.presentViewController(activityVC, animated: true, completion: nil)
}
like image 663
Loanb222 Avatar asked Apr 09 '15 23:04

Loanb222


2 Answers

The UIActivityViewController's has non-null popoverPresentationController property when running on iPad. So, try below.

if let wPPC = activityVC.popoverPresentationController {
    wPPC.sourceView = some view
    //  or
    wPPC.barButtonItem = some bar button item
}
presentViewController( activityVC, animated: true, completion: nil )
like image 85
Satachito Avatar answered Oct 24 '22 23:10

Satachito


Building on @Satachito's answer: As the sourceView you can create an (invisible) CGRect at the place the popup should point to, and set the arrow in that direction:

let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)

if UIDevice.current.userInterfaceIdiom == .pad {
    activityVC.popoverPresentationController?.sourceView = UIApplication.shared.windows.first
    activityVC.popoverPresentationController?.sourceRect = CGRect(x: 0, y: 0, width: 300, height: 350)
    activityVC.popoverPresentationController?.permittedArrowDirections = [.left]
}

UIApplication.shared.windows.first?.rootViewController?.present(activityVC, animated: true, completion: nil)
like image 3
Jannik Arndt Avatar answered Oct 25 '22 01:10

Jannik Arndt