3

我正在创建一个 iOS 应用程序,用户可以通过它在他们的设备上打印文件。在我的应用程序中,我可以DocumentPicker通过其他应用程序(如 iCloud Drive、Dropbox 等)提供的访问设备上的文件。

现在,我想添加一个功能,用户可以通过其他应用程序与我的应用程序共享文件。我为此创建了一个Action Extension。例如,如果我在照片应用程序中选择一个图像并选择Share我在共享表中获取我的扩展名,当我选择它时,我也会得到文件的 URL。接下来,我正在创建此文件的 zip 文件以将其发送到我的服务器。但问题是,zip 文件总是空的。我正在使用的代码如下:

在 Action Extension 的 viewDidLoad() 中

if itemProvider.hasItemConformingToTypeIdentifier(kUTTypeImage as String) {
    itemProvider.loadItemForTypeIdentifier(kUTTypeImage as String, options: nil, 
        completionHandler: { (image, error) in
            NSOperationQueue.mainQueue().addOperationWithBlock {
                print("Image: \(image.debugDescription)")
                //Image: Optional(file:///Users/guestUser/Library/Developer/CoreSimulator/Devices/00B81632-041E-47B1-BACD-2F15F114AA2D/data/Media/DCIM/100APPLE/IMG_0004.JPG)
                print("Image class: \(image.dynamicType)")
                //Image class: Optional<NSSecureCoding>
                self.filePaths.append(image.debugDescription)
                let zipPath = self.createZip(filePaths)
                print("Zip: \(zipPath)")
            }
         })
}

我的createZip功能如下:

func createZipWithFiles(filePaths: [AnyObject]) -> String {
    let zipPath = createZipPath()  //Creates an unique zip file name

    let success = SSZipArchive.createZipFileAtPath(zipPath, withFilesAtPaths: filePaths)

    if success {
        return zipPath
    }
    else {
        return "zip prepation failed"
    }
}

有没有办法可以创建共享文件的 zip?

4

1 回答 1

3

您的主要问题是您盲目地添加image.debugDescription到需要文件路径的数组中。的输出image.debugDescription根本不是有效的文件路径。您需要使用适当的函数image来获取实际的文件路径。

但是image被声明为具有NSSecureCoding. 根据 的输出image.debugDescription,似乎image确实是 type NSURL。因此,您需要使用以下行转换image为:NSURL

if let photoURL = image as? NSURL {
}

拥有 后NSURL,您可以使用该path属性来获取实际需要的路径。

所以你的代码变成:

if itemProvider.hasItemConformingToTypeIdentifier(kUTTypeImage as String) {
    itemProvider.loadItemForTypeIdentifier(kUTTypeImage as String, options: nil, 
        completionHandler: { (image, error) in
            if let photoURL = image as? NSURL {
                NSOperationQueue.mainQueue().addOperationWithBlock {
                    let photoPath = photoURL.path
                    print("photoPath: \(photoPath)")
                    self.filePaths.append(photoPath)
                    let zipPath = self.createZip(filePaths)
                    print("Zip: \(zipPath)")
                }
            }
    })
}

提示:切勿用于陈述debugDescription以外的任何内容。print它的输出只是一些可能包含几乎任何信息的字符串,并且该输出可以从一个 iOS 版本更改为下一个版本。

于 2016-04-25T15:08:21.560 回答