3
votes

I have added a Share Extension to my iOS app, and have created a custom UI using UIViewController, NOT the default SLComposeServiceViewController. The UI is working, but how do I refer to the files that were chosen to be shared? For instance, if I hit share on a photo, how do I refer to that photo, and convert it to NSData. I currently have this code, but when it runs, data never seems to be initialized. What am I doing wrong?

    //Runs when button is pressed
    inputItem = extensionContext!.inputItems.first as NSExtensionItem
    attachment = inputItem.attachments![0] as NSItemProvider
    attachment.loadItemForTypeIdentifier(kUTTypeJPEG as String,
        options: nil,
        completionHandler: {(content, error: NSError!) in
            let url = content as? NSURL
            if let data = NSKeyedArchiver.archivedDataWithRootObject(url!) as NSData?{
                self.imageChosen = UIImage(data: data)!
                //Never runs
            }
            else {
                //Always runs
            }

    })

Also, how do I make the extension button disappear when the chosen attachment contains more than one file (photo or video), or is an invalid file type. Any answer is appreciated. Thanks in advance.

1
What does the NSExtensionActivationRule look like for this extension?Tom Harrington

1 Answers

0
votes

This is how I prefer to share images and files:

//when the share button is pressed, default share phrase is added, cropped image of highscore is added

    var sharingItems = [AnyObject]()

    var shareButtonHighscore = NSUserDefaults.standardUserDefaults().objectForKey("highscore") as Int!

    sharingItems.append("I am sharing \(shareButtonHighscore)!")

    UIGraphicsBeginImageContextWithOptions(UIScreen.mainScreen().bounds.size, false, 0);
    self.view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
    var image:UIImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    sharingItems.append(image)

    let activityViewController = UIActivityViewController(activityItems: sharingItems, applicationActivities: nil)

    activityViewController.excludedActivityTypes = [UIActivityTypeCopyToPasteboard,UIActivityTypeAirDrop,UIActivityTypeAddToReadingList,UIActivityTypeAssignToContact,UIActivityTypePostToTencentWeibo,UIActivityTypePostToVimeo,UIActivityTypePrint,UIActivityTypeSaveToCameraRoll,UIActivityTypePostToWeibo]

    self.presentViewController(activityViewController, animated: true, completion: nil)

Hope this helps!