举例以下Swift代码
class ShareManager {
static func share() {
let items: [Any] = ["https://www.baidu.com"]
let activity = UIActivityViewController(activityItems: items, applicationActivities: nil)
UIApplication.shared.windows[0].rootViewController?.present(activity, animated: true) { }
}
}
函数share
在iPhone上运行正常,然而在iPad上运行就会崩溃,崩溃详情如下:
Terminating app due to uncaught exception ‘NSGenericException’, reason: ‘UIPopoverPresentationController (<UIPopoverPresentationController: 0x108814c50>) should have a non-nil sourceView or barButtonItem set before the presentation occurs.’
terminating with uncaught exception of type NSException
造成崩溃的原因,是因为iPad弹出窗口采用的是popover的展示模式,该模式要求提供sourceView
和sourceRect
。
所以share
函数代码修改如下
static func share() {
let items: [Any] = ["https://www.baidu.com"]
let activity = UIActivityViewController(activityItems: items, applicationActivities: nil)
/* 针对iPad追加部分 Begin */
if UIDevice.current.model.lowercased() == "ipad" {
let sourceView = UIApplication.shared.windows[0].rootViewController!.view
var frame = sourceView!.frame
frame.size.height /= 2
frame.origin.x = 0
frame.origin.y = 0
activity.popoverPresentationController?.sourceView = sourceView
activity.popoverPresentationController?.sourceRect = frame
activity.popoverPresentationController?.permittedArrowDirections = .up
}
/* 针对iPad追加部分 End */
UIApplication.shared.windows[0].rootViewController?.present(activity, animated: true) { }
}
问题解决。
移动应用开发小伙伴可以在我的公众号风海铜锣的加群菜单栏中申请加群完成加群申请,一起共同进步。