据我测试,在某些情况下,data 中会有一个Data。因此,如果您不想为此方法编写 Objective-C 包装器,则可能需要编写类似的内容:
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 中,您可以将带有 (UIImage *item, NSError *error) 的 Objective-C 块传递给 loadItemForTypeIdentifier:options:completionHandler: 的 completionHandler。在这种情况下,项目提供者会尝试将各种图像数据转换为UIImage。
NSItemProviderCompletionHandler
讨论
...
项目
要加载的项目。指定块时,将此参数的类型设置为您想要的特定数据类型。 ...项目提供者尝试将数据强制转换为您指定的类。
所以,如果您不介意编写一些 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 编写功能请求。