Friday, September 12, 2014

Cross-secting the ImageInverter Extension WWDC sample

In this sample, the main View Controller AAPLImageShareVC.m utilises the storyboard and it has an image in it. There is a share button, and clicking on the share button, below is the code

UIActivityController *activityController = [UIActivityCotnroller alloc]initWithActivityItems:@[[imageView image]] applicationActivities:nil]; 
UIActivityController was discussed in detail with the AirDrop programming, This basically shows up the list of applications that can handle the data. With iOS 8.0, extension also get listed here. 

When an extension is selected, the image is passed as extension item to the invoked one. 

The code in the extension is like below 

the UIViewController is having the extensionContext and we can get the object from the extension item like below 

NSExtensionItem *imageItem = [self.extensionItems.inputItems firstObject];
// now get the item provider from the extension object

NSItemProvider *imageItemProvider = [imageItem attachments firstObject];

Now we can check if the item provider is conforming to the image UTI

imageItemProvider hasItemsConformingToTypeIdentifier: (NSString*)kUTTypeImage

imageItemProvider has a method loadItemForTypeIdentifier which will load the image from the ImageItemProvider in a completion block. 
Once the image is retrieved, this can be set in the view so that the extension displays this information 

Now, when the extension is done, then application can post the data back to caller of the extension in the below way. 

NSExtensionItem *extensionItem = [NSExtensionItem alloc]init];
extensionItem setAttributeTitle:[[NSAttributedString alloc]initWithString:@"Inverted Image"];
extensionItem setAttachments:[NSItemProvider alloc] initWithItem:[imageView image] typeIdentifier:(NSSTring*)kUTTypeImage
];
[self.extensionContext completeRequestReturningItems:@[extensionItem] completionHandler:nil];

If it is to cancel without doing any action, below code can be used 


[self.extensionContext cancelRequestWithError:[NSError errorWithDomain:@"ImageInverterErrorDomain"] code:0 userInfo:nil];

references: 

No comments:

Post a Comment