我之前是用objective-c的。下面的 Objective C 代码运行良好:
in. h
@property (retain)UIDocumentInteractionController *docController;
并以 .m 为单位
NSString *path = [[NSBundle mainBundle] pathForResource:@"book" ofType:@"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
docController = [UIDocumentInteractionController interactionControllerWithURL:targetURL];
if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"itms-books:"]]) {
[docController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
NSLog(@"iBooks installed");
} else {
NSLog(@"iBooks not installed");
}
但现在我尝试使用 swift 打开,这是我的 swift 代码:
if let path = NSBundle.mainBundle().pathForResource("book", ofType: "pdf") {
if let targetURL = NSURL.fileURLWithPath(path) {
let 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")
}
}
}
但当我选择 iBooks 打开 pdf 时,它崩溃了。谁能帮我!
我认为 Bojan Macele 有一个很好的答案,我使用了他的代码,我只是认为它需要一些解释。我也遇到了应用程序崩溃的问题。只需确保 docController 是在您想要使用它的函数之外声明的。我在我的类声明下声明了这个变量。
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()
// Dispose of any resources that can be recreated.
}
}
所以我只是做了一个演示项目来让它工作。就是这个。需要在函数外部声明它的原因是为了内存管理问题。一旦程序到达buttonPressed的末尾,它就不再知道docController是什么。然后,它尝试使用 docController 打开 iBooks,这是一个非持久变量,因此它崩溃了。
希望这可以帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)