Skip to content

Instantly share code, notes, and snippets.

@uruly
Created April 13, 2018 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uruly/aaac94251ffe4bde26c805bb70f52cb8 to your computer and use it in GitHub Desktop.
Save uruly/aaac94251ffe4bde26c805bb70f52cb8 to your computer and use it in GitHub Desktop.
//渡したい画像
class ImageActivityItem:NSObject,UIActivityItemSource{
var image:UIImage?
override init(){
super.init()
}
convenience init(_ image:UIImage?){
self.init()
self.image = image
}
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return image ?? UIImage()
}
func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivityType?) -> Any? {
if activityType?.rawValue == "com.burbn.instagram.shareextension"{
//例えばここで真四角に切り取り処理をするとか。
let ref = image!.cgImage!.cropping(to: CGRect(x:0,y:0,width:100,height:100))
let cropImage = UIImage(cgImage: ref!, scale: self.image!.scale, orientation: image!.imageOrientation)
return cropImage
}
return image
}
}
//渡したいテキスト
class TextActivityItem:NSObject,UIActivityItemSource{
var shareText = ""
override init(){
super.init()
}
convenience init(_ text:String){
self.init()
self.shareText = text
}
func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivityType?) -> Any? {
//Twitter投稿時のみハッシュタグをつける
if activityType == .postToTwitter {
return shareText + "#ハッシュタグ"
}
return shareText
}
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
//ここではNSObjectを返しておく
return NSObject()
}
}
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let btn = UIButton(frame:CGRect(x:0,y:350,width:100,height:100))
btn.addTarget(self, action: #selector(self.btnTapped(sender:)), for: .touchUpInside)
btn.backgroundColor = UIColor.red
self.view.addSubview(btn)
}
//ボタンが押されたとき
@objc func btnTapped(sender:UIButton){
let text = "シェアするテキスト"
let image = UIImage(named:"image1.png")
let activityItem:[Any] = [TextActivityItem(text),ImageActivityItem(image)]
let activityVC = UIActivityViewController(activityItems: activityItem, applicationActivities: nil)
self.present(activityVC, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment