我的主要问题是处理NSItemProvider的数据类型.
这是问题所在:根据我启动扩展程序的应用程序,我得到了不同类型的数据.例如:
我告诉申请:
let IMAGE_TYPE = kUTTypeImage as String
if attachment.hasItemConformingToTypeIdentifier(IMAGE_TYPE){
attachment.loadItem(forTypeIdentifier: IMAGE_TYPE,options: nil){ data,error in
...
}
(注意:附件的类型为NSItemProvider)
从照片应用程序执行时,数据是一个URL,所以我从中创建一个UIImage并继续.
问题是,对于某些应用程序,数据已经是UIImage,我无法找到如何区分大小写.
最好的方法可能是检查数据对象的数据类型,但至少对我来说并不是微不足道的.
在此先感谢您的帮助!
解决方法
if attachment.hasItemConformingToTypeIdentifier(IMAGE_TYPE) {
attachment.loadItem(forTypeIdentifier: IMAGE_TYPE,options: nil) { data,error in
let myImage: UIImage?
switch data {
case let image as UIImage:
myImage = image
case let data as Data:
myImage = UIImage(data: data)
case let url as URL:
myImage = UIImage(contentsOfFile: url.path)
default:
//There may be other cases...
print("Unexpected data:",type(of: data))
myImage = nil
}
//...
}
}
(未经测试,您可能需要修复某些部件.)
在Objective-C中,您可以将一个Objective-C块(UIImage * item,NSError * error)传递给loadItemForTypeIdentifier的completionHandler:options:completionHandler:.在这种情况下,项目提供程序尝试将所有排序的图像数据转换为UIImage.
NSItemProviderCompletionHandler
discussion
…
item
The item to be loaded. When specifying your block,set the type of this parameter to the specific data type you want. … The item provider attempts to coerce the data to the class you specify.
所以,如果你不介意编写一些Objective-C包装器,你可以写这样的东西:
NSItemProvider Swift.h:
@import UIKit;
typedef void (^NSItemProviderCompletionHandlerForImage)(UIImage *image,NSError *error);
@interface NSItemProvider(Swift)
- (void)loadImageForTypeIdentifier:(Nsstring *)typeIdentifier
options:(NSDictionary *)options
completionHandler:(NSItemProviderCompletionHandlerForImage)completionHandler;
@end
NSItemProvider Swift.m:
#import "NSItemProvider+Swift.h"
@implementation NSItemProvider(Swift)
- (void)loadImageForTypeIdentifier:(Nsstring *)typeIdentifier
options:(NSDictionary *)options
completionHandler:(NSItemProviderCompletionHandlerForImage)completionHandler {
[self loadItemForTypeIdentifier:typeIdentifier
options:options
completionHandler:completionHandler];
}
@end
{YourProject} -Bridging-Header.h:
#import "NSItemProvider+Swift.h"
并使用Swift作为:
if attachment.hasItemConformingToTypeIdentifier(IMAGE_TYPE) {
attachment.loadImage(forTypeIdentifier: IMAGE_TYPE,options: nil) { myImage,error in
//...
}
}
在我看来,Apple应提供NSItemProvider的这种类型安全扩展,您可以使用Apple的Bug Reporter编写功能请求.