从iOS应用程序发出与MS Excel的深层链接

时间:2018-03-13 22:02:48

标签: ios swift deep-linking

我正在尝试打开位于服务器上的Excel文档。我编写了以下代码,但它总是为UIApplication.shared.canOpenURL(url as URL)

返回false

我认为我缺少深度链接到Excel的一些要求。为什么iOS无法理解ms-excel:ofe|u|格式?

@objc static func openExcel() {

    let originalString = "http://s000.tinyupload.com/download.php?file_id=23290165129849240725&t=2329016512984924072514118"
    let encodedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
    let encodedURLString = "ms-excel:ofe|u|" + encodedString! + "|n|TestDoc.xlsx|a|App"

    if let url = NSURL(string: encodedURLString), 
        UIApplication.shared.canOpenURL(url as URL) {
        UIApplication.shared.openURL(url as URL)
    } else if let itunesUrl = NSURL(string: "https://itunes.apple.com/us/app/microsoft-excel/id586683407?mt=8&uo=4"), UIApplication.shared.canOpenURL(itunesUrl as URL) {
        UIApplication.shared.openURL(itunesUrl as URL)
    }
}

2 个答案:

答案 0 :(得分:2)

我已经分析了你的代码并发现了一些错误。首先,您的URL重定向到某个地方,根据Microsoft文档,它无法处理重定向URL

  

必须对URL进行编码,并且必须是文件的直接链接(不是   重定向)。如果URL采用Office无法处理的格式,或者   下载完全失败,Office不会将用户返回到调用   应用

这是Microsoft Documentation Link

第二个错误是您只编码包含站点URL的URL字符串,您应该将方案ms-excel:之后的部分视为URL并且应该进行编码。

由于编码不正确导致let url = URL(string: encodedURLString)结果nil导致其无法按预期运行。

以下是一个示例工作代码:

 @objc static func openExcel() {
        //replace the below url with yours. may be this one dosen't work
        let originalString = "ofe|u|https://pgcconline.blackboard.com/webapps/dur-browserCheck-bb_bb60/samples/sample.xlsx" 
        let encodedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        let encodedURLString = "ms-excel:" + encodedString!

        if let url = URL(string: encodedURLString),
            UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.openURL(url)
        } else if let itunesUrl = NSURL(string: "https://itunes.apple.com/us/app/microsoft-excel/id586683407?mt=8&uo=4"), UIApplication.shared.canOpenURL(itunesUrl as URL) {
            UIApplication.shared.openURL(itunesUrl as URL)
        }
    }

注意:从iOS 9开始,您必须将{@ 1}}下Info.plist下{@ 1}}要查询的任何网址方案列入白名单:

例如在我们的案例中:

enter image description here

答案 1 :(得分:0)

当我尝试打开URL in the question above时,我会被重定向到this URL,所以我的猜测是您的代码很好,可能是您尝试打开的excel文件是实际上是一个HTML页面,因为tinyupload显然会阻止指向文件的直接链接。

也许尝试打开直接excel文件下载链接,https://pgcconline.blackboard.com/webapps/dur-browserCheck-bb_bb60/samples/sample.xlsx(这是'xlsx file sample download'的第一个google结果)