|
// |
|
// ShareObject.swift |
|
// |
|
// Created by Kalpesh Talkar on 28/05/16. |
|
// Copyright © 2016 Kalpesh. All rights reserved. |
|
// |
|
|
|
import UIKit |
|
|
|
@IBDesignable class ShareObject: NSObject { |
|
|
|
// MARK: - variables |
|
@IBOutlet weak var viewController: UIViewController! |
|
@IBOutlet weak var barButtonItem: UIBarButtonItem? |
|
@IBOutlet weak var sourceView: UIView? |
|
|
|
@IBInspectable var shareText : String? |
|
@IBInspectable var isUrl : Bool = false |
|
@IBInspectable var shareImage : UIImage? |
|
|
|
// MARK:- init methods |
|
override init() { |
|
super.init() |
|
} |
|
|
|
init(viewController: UIViewController, sourceView: UIView) { |
|
super.init() |
|
self.viewController = viewController |
|
self.sourceView = sourceView |
|
} |
|
|
|
init(viewController: UIViewController, barButtonItem: UIBarButtonItem) { |
|
super.init() |
|
self.viewController = viewController |
|
self.barButtonItem = barButtonItem |
|
} |
|
|
|
// MARK: - share methods |
|
@IBAction func share(sender: AnyObject) { |
|
var shareData : [AnyObject] = [] |
|
|
|
if shareText != nil && shareText! != "" { |
|
if isUrl { |
|
let url = NSURL(string: shareText!) |
|
if url != nil && UIApplication.sharedApplication().canOpenURL(url!) { |
|
shareData.append(url!) |
|
} else { |
|
shareData.append(shareText!) |
|
} |
|
} else { |
|
shareData.append(shareText!) |
|
} |
|
} |
|
|
|
if shareImage != nil { |
|
shareData.append(shareImage!) |
|
} |
|
|
|
shareContents(shareData) |
|
} |
|
|
|
func shareText(text : String) { |
|
shareContents([text]) |
|
} |
|
|
|
func shareURL(url : NSURL) { |
|
shareContents([url]) |
|
} |
|
|
|
func shareImage(image : UIImage) { |
|
shareContents([image]) |
|
} |
|
|
|
func shareContents(shareData : [AnyObject]) { |
|
if shareData.count > 0 { |
|
let activityVC = UIActivityViewController(activityItems: shareData, applicationActivities: nil) |
|
if barButtonItem != nil { |
|
activityVC.popoverPresentationController?.barButtonItem = barButtonItem |
|
} |
|
if sourceView != nil { |
|
activityVC.popoverPresentationController?.sourceView = sourceView |
|
} |
|
viewController.presentViewController(activityVC, animated: true, completion: nil) |
|
|
|
} else { |
|
let alert = UIAlertController(title: "Error", message: "Unable to launch share activity. No contents selected to share", preferredStyle: .Alert) |
|
let ok = UIAlertAction(title: "OK", style: .Default, handler: nil) |
|
alert.addAction(ok) |
|
viewController.presentViewController(alert, animated: true, completion: nil) |
|
} |
|
} |
|
|
|
} |