无法分享截图&使用UIActivityViewController

时间:2015-10-20 18:51:16

标签: ios facebook swift uiactivityviewcontroller

我正在使用UIActivityViewController分享文字,屏幕截图和网址。它适用于Twitter,电子邮件,短信等。事实上除了Facebook以外的一切。

据我了解,Facebook不再允许共享预填充文本,因此我希望只分享屏幕截图和网址。但是当用户选择Facebook时,出现的图像是直接从URL获取的图像而不是我指定的图像(即屏幕截图)。 {www.3}当我使用www.google.com作为网址时会发生什么。

如果我没有包含网址,那么屏幕截图看起来很好,但实际上它只是分享一张照片(这就是它在Facebook上显示的方式,说“John Doe添加了一张新照片”然后我的屏幕截图显示)。无论我是否登录Facebook应用程序,都会发生这种情况。

这是我的代码:

@IBAction func shareButton(sender: AnyObject) {
  // Get screenshot
  UIGraphicsBeginImageContextWithOptions(UIScreen.mainScreen().bounds.size, false, 0)
  self.view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
  let screenshot:UIImage = UIGraphicsGetImageFromCurrentImageContext()
  UIGraphicsEndImageContext()

  let textToShare = "My text here"
  let myWebsite = NSURL(string: "http://www.example.com/")

  socialShare(sharingText: textToShare, sharingImage: screenshot, sharingURL: myWebsite)
}

然后:

func socialShare(sharingText sharingText: String?, sharingImage: UIImage?, sharingURL: NSURL?) {
  var sharingItems = [AnyObject]()

  if let text = sharingText {
    sharingItems.append(text)
  }

  if let image = sharingImage {
    sharingItems.append(image)
  }

  if let url = sharingURL {
    sharingItems.append(url)
  }

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

  // Excluded sharing options
  activityViewController.excludedActivityTypes = [UIActivityTypeCopyToPasteboard,UIActivityTypeAirDrop,UIActivityTypeAddToReadingList,UIActivityTypeAssignToContact,UIActivityTypePostToTencentWeibo,UIActivityTypePostToVimeo,UIActivityTypePrint,UIActivityTypePostToWeibo]

  // The popover needs additional code to work on iPad, so distinguish between iPhone & iPad
  if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Phone) { // If iPhone
    self.presentViewController(activityViewController, animated: true, completion: nil)
  } else { // If iPad
    let popoverCntlr = UIPopoverController(contentViewController: activityViewController)
    popoverCntlr.presentPopoverFromRect(CGRectMake(self.view.frame.size.width - 40, 80, 0, 0), inView: self.view, permittedArrowDirections: UIPopoverArrowDirection.Up, animated: true) // position where the popover appears
  }
}

那么有人知道如何使用UIActivityViewController通过Facebook分享屏幕截图和网址吗?我怀疑这个问题是由Facebook结束引起的,因为Twitter等一切正常,但是有解决方法吗?

3 个答案:

答案 0 :(得分:0)

Facebook禁用了同时共享文字和图片的功能。

答案 1 :(得分:0)

我不完全确定这是来自Facebook方面。我在尝试发布网址和图片时遇到了完全相同的问题。我看到与您使用设备(包括您的屏幕截图)相同的行为,但它通过Xcode模拟器完美地工作。我没有在API中找到任何证据表明Facebook不会同时接受URL和照片。如果您可以验证相同,将会很有帮助。顺便说一句,我的Xcode版本是7.3

答案 2 :(得分:0)

我不确定截图,但我们可以与Facebook分享网址。更好的方法是对UIActivityItemProvider进行子类化,好处是我们还可以跟踪已挖掘的项目(活动)。我在这里粘贴了我的Objective-C代码,它可能对你有所帮助。

- (void)showShareSheetWithShareText:(NSString *)shareText onView:(UIViewController *)parentViewController{

@try {

    if ([shareText length] == 0) {

        shareText = @"Default Text";
    }

    dispatch_async(dispatch_get_main_queue(), ^{

        ActivityItemProvider *activityItem = [[ActivityItemProvider alloc] initWithPlaceholderItem:shareText]; // Sub class of UIActivityItemProvider

        UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:@[shareText, activityItem] applicationActivities:nil];
        NSMutableArray *arrExcludeActivities = [[NSMutableArray alloc] initWithObjects:
                                                UIActivityTypePostToWeibo,
                                                UIActivityTypePrint,
                                                UIActivityTypeCopyToPasteboard,
                                                UIActivityTypeAssignToContact,
                                                UIActivityTypeSaveToCameraRoll,
                                                UIActivityTypeAirDrop,
                                                UIActivityTypeAddToReadingList,
                                                UIActivityTypePostToFlickr,
                                                UIActivityTypePostToVimeo,
                                                UIActivityTypeOpenInIBooks,
                                                UIActivityTypePostToTencentWeibo, nil];
        //            @"com.apple.mobilenotes.SharingExtension",
        //            @"com.apple.reminders.RemindersEditorExtension"

        activityVC.excludedActivityTypes = arrExcludeActivities;

        if ([activityVC respondsToSelector:@selector(completionWithItemsHandler)]) {

            activityVC.completionWithItemsHandler = ^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {

                if (completed) {

                    // Log Events
                }
                else{
                    // Show error
                }
            };
        }
        else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
            // Deprecated in iOS 8.  Safe to hide deprecation warnings as the new completion handler is checked for above
            activityVC.completionHandler = ^(UIActivityType __nullable activityType, BOOL completed){

                // Write code for below iOS 8.
            };
#pragma clang diagnostic pop
        }

        UIViewController *presentingViewController;
        if (parentViewController && parentViewController != nil) {

            presentingViewController = parentViewController;
        }
        else{

            presentingViewController = [[[UIApplication sharedApplication].delegate window] rootViewController];
        }

        if (presentingViewController) {
            // Required for iPad/Universal apps on iOS 8+
            if ([presentingViewController respondsToSelector:@selector(popoverPresentationController)]) {
                activityVC.popoverPresentationController.sourceView = presentingViewController.view;
            }

            [presentingViewController presentViewController:activityVC animated:YES completion:nil];
        }
        else {
            NSLog(@"[warning, fatal] No view controller is present to show the share sheet. Aborting.");
        }
    });
}
@catch (NSException *exception) {

    // Catch Exception
 }
}

现在是.h头文件的UIActivityItemProvider子类

@interface ActivityItemProvider : UIActivityItemProvider

@end

和.m实施文件

@implementation ActivityItemProvider

- (id) initWithPlaceholderItem:(id)placeholderItem {

    self = [super initWithPlaceholderItem:placeholderItem];
    return self;
}

- (id)item {

    NSString *channel = [ActivityItemProvider humanReadableChannelWithActivityType:self.activityType];

    NSArray *scrapers = @[@"Facebook", @"Twitter", @"Slack", @"Apple Notes"];
    for (NSString *scraper in scrapers) {

       if ([channel isEqualToString:scraper]) {

           // Do something for these Channels if you want.
    }
 }

 return [NSURL URLWithString:@"Your Site URL"]; // return type should be NSURL else the activity does consider as a normal string.
}

+ (NSString *)humanReadableChannelWithActivityType:(NSString *)activityString {

NSString *channel = activityString; //default
NSDictionary *channelMappings = [[NSDictionary alloc] initWithObjectsAndKeys:
                                 @"Facebook", UIActivityTypePostToFacebook,
                                 @"Twitter", UIActivityTypePostToTwitter,
                                 @"Weibo", UIActivityTypePostToWeibo, // May not use.
                                 @"SMS", UIActivityTypeMessage,
                                 @"Email", UIActivityTypeMail,

                                 @"Print", UIActivityTypePrint,
                                 @"Pasteboard", UIActivityTypeCopyToPasteboard,
                                 @"Contact",UIActivityTypeAssignToContact,
                                 @"CameraRoll", UIActivityTypeSaveToCameraRoll,
                                 @"Reading List", UIActivityTypeAddToReadingList,
                                 @"flickr", UIActivityTypePostToFlickr,
                                 @"Vimeo", UIActivityTypePostToVimeo,
                                 @"Tencent Weibo", UIActivityTypePostToTencentWeibo,
                                 @"AirDrop",UIActivityTypeAirDrop,
                                 @"Books",UIActivityTypeOpenInIBooks,

                                 @"Apple Reminders", @"com.apple.reminders.RemindersEditorExtension",
                                 @"Apple Notes", @"com.apple.mobilenotes.SharingExtension",
                                 @"Slack", @"com.tinyspeck.chatlyio.share",
                                 @"WhatsApp", @"net.whatsapp.WhatsApp.ShareExtension",
                                 @"WeChat", @"com.tencent.xin.sharetimeline",
                                 @"LINE", @"jp.naver.line.Share",
                                 @"Pinterest", @"pinterest.ShareExtension",
                                 nil
                                 ];
  // Set to a more human readible string if we can identify it
  if ([channelMappings objectForKey:activityString]) {
    channel = channelMappings[activityString];
  }
  return channel; // [channel uppercaseString];
}

// For email subject
- (NSString *)activityViewController:(UIActivityViewController *)activityViewController subjectForActivityType:(nullable UIActivityType)activityType{

  return @"Your Email Subject";
}

@end