我正在创建一个 iOS 应用程序,用户可以通过它在他们的设备上打印文件。在我的应用程序中,我可以通过 iCloud Drive、Dropbox 等其他应用程序提供的 DocumentPicker
访问设备上的文件。
现在,我想添加一项功能,用户可以通过其他应用程序与我的应用程序共享文件。我为此创建了一个 Action Extension
。
例如,如果我在照片应用程序中选择一个图像并选择 Share
,我会在 Share 表中获得我的扩展名,当我选择它时,我还会获得文件的 URL。接下来,我正在创建此文件的 zip 文件以将其发送到我的服务器。但问题是,zip 文件总是空的。我使用的代码如下:
In 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 文件?
最佳答案
您的主要问题是您盲目地将 image.debugDescription
添加到需要文件路径的数组中。 image.debugDescription
的输出根本不是有效的文件路径。您需要在 image
上使用适当的函数来获取实际文件路径。
但是 image
被声明为具有 NSSecureCoding
类型。根据 image.debugDescription
的输出,image
似乎确实是 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 版本更改为下一个。
关于iOS 将文件导入我的应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36604103/