问题
I am writing a share extension, but my closure that would capture and save the shared attachment is not running. How can I find out why? The switch branch executes, the attachment is there. There is no error message, it just never runs.
if let contents = content.attachments as? [NSItemProvider] {
for attachment in contents {
let fType = attachment.registeredTypeIdentifiers[0]
if attachment.hasItemConformingToTypeIdentifier(fType) {
switch fType {
case kUTTypeImage as String as String:
do {
attachment.loadItem(forTypeIdentifier: fType, options: nil, completionHandler: { data, error in
print("AppImage")
let url = data as! URL
if let imageData = try? Data(contentsOf: url) {
self.appImage = UIImage(data: imageData)
self.saveImage(image: self.appImage!)
}
})
} // public image case
回答1:
Once completeRequestReturningItems (CRRI) is executed, your completion handlers for loadItem will no longer be called (they are effectively canceled at that point). Therefore you must synchronize your asynchronous tasks to ensure that you don't execute CRRI until your completion handlers have finished or until you no longer care. From your comments, it sounds like you are invoking loadItem and immediately proceeding to call CRRI.
See answers to this related question: iOS 8 Share extension loadItemForTypeIdentifier:options:completionHandler: completion closure not executing
I prefer the answer there that uses a dispatch group.
来源:https://stackoverflow.com/questions/49174303/swift-loaditem-closure-not-running