I think that Boyan Masel had a great answer, and I used his code, I just think he needs some explanation. I also had problems with the application crashing. Just make sure the docController is declared outside the function in which you want to use it. I have this variable declared directly under my class declaration.
import UIKit class ViewController: UIViewController { var button : UIButton? var docController: UIDocumentInteractionController? override func viewDidLoad() { super.viewDidLoad() button = UIButton(frame: CGRectMake(10, 50, 100, 50)) button?.backgroundColor = UIColor.blackColor() self.view.addSubview(button!) button?.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchDown) } func buttonPressed(sender: UIButton){ println("button pressed") if let path = NSBundle.mainBundle().pathForResource("test", ofType: "pdf") { if let targetURL = NSURL.fileURLWithPath(path) { docController = UIDocumentInteractionController(URL: targetURL) let url = NSURL(string:"itms-books:"); if UIApplication.sharedApplication().canOpenURL(url!) { docController!.presentOpenInMenuFromRect(CGRectZero, inView: self.view, animated: true) println("iBooks is installed") }else{ println("iBooks is not installed") } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning()
So, I just did a demo project to make it work. This is it. The reason it should be declared out of function is related to memory management issues. As soon as the program reaches the end of the "Subscribe" button, it no longer knows what docController is. He then tries to open iBooks using docController, which is a non persistent variable, so it crashes.
Hope this helps.
source share