如何使用UIActivityViewController共享活动的不同项目?

时间:2015-06-18 05:19:09

标签: ios iphone swift

我需要为活动类型分享不同的项目。 对于Facebook:我必须分享:text&网址。 但是对于Mail:我必须分享文字,图片和图片。网址。

我见过很多问题,但没有人回答我的疑问。

下面是一段代码,我是如何做到的。

@IBAction func shareDetails(sender: AnyObject) {

    var activityItemsArray:[AnyObject] = [SharingProvider(source: detail)]
    if let urlString = dealer.websiteURL {
        if let url = NSURL(string:urlString) {
            activityItemsArray.append(url)
        }
    }

    let shareVC = UIActivityViewController(activityItems: activityItemsArray, applicationActivities: nil)
    shareVC.setValue("This is the Subject", forKey: "subject")

    shareVC.completionWithItemsHandler = { (activityType:String!, completed:Bool, returnedItems:[AnyObject]!, error:NSError!) -> Void in
        if !completed {
            return
        }
    }

    self.presentViewController(shareVC, animated: true, completion: nil)
}

我想根据activityType自定义activityItemArray。 任何帮助将不胜感激。 :)

1 个答案:

答案 0 :(得分:1)

方法是使用UIActivityViewController,例如以下方式:

@IBAction func shareSheet(sender: AnyObject) {

let firstActivityItem = "Text you want"
let secondActivityItem : NSURL = NSURL(string: "http//:urlyouwant")!
// If you want to put an image
let image : UIImage = UIImage(named: "image.jpg")!

let activityViewController : UIActivityViewController = UIActivityViewController(
    activityItems: [firstActivityItem, secondActivityItem, image], applicationActivities: nil)

// This lines is for the popover you need to show in iPad 
activityViewController.popoverPresentationController?.sourceView = (sender as! UIButton)

// This line remove the arrow of the popover to show in iPad
activityViewController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.allZeros
activityViewController.popoverPresentationController?.sourceRect = CGRect(x: 150, y: 150, width: 0, height: 0)

// Anything you want to exclude
activityViewController.excludedActivityTypes = [
    UIActivityTypePostToWeibo,
    UIActivityTypePrint,
    UIActivityTypeAssignToContact,
    UIActivityTypeSaveToCameraRoll,
    UIActivityTypeAddToReadingList,
    UIActivityTypePostToFlickr,
    UIActivityTypePostToVimeo,
    UIActivityTypePostToTencentWeibo
]

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

上述代码适用于iPhone和iPad,因为在iOS 8中设置新的popoverPresentationController它也适用于iPad。

如果使用UIBarButtonItem,您需要替换此行:

activityViewController.popoverPresentationController?.sourceView = (sender as! UIButton)

有了这个:

activityViewController.popoverPresentationController?.barButtonItem = (sender as! UIBarButtonItem)

我希望这对你有所帮助。

Source