我们将编写一个简单的应用程序,让我们在相册选择一个图片,并分享我们的应用程序。
这个程序允许我们从相册中选择一张照片,我们也会选择一个颜色与照片,我们也可以选择默认的。
1.激活share extentions
打开plist文件,添加一下代码:
<key>NSExtensionAttributes</key>
<dict>
<key>NSExtensionActivationRule</key>
<dict>
<key>NSExtensionActivationSupportsImageWithMaxCount</key>
<integer>1</integer>
</dict>
</dict>
2.实现share extentions
创建一个RedViewController继承UIViewController,添加ImageView
import UIKit
import Photos
class RedViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
let suiteName = "paul.share.extension"
let redDefaultKey = "RedColorImage"
//将图片保存在NSUserDefaults中
override func viewDidLoad() {
super.viewDidLoad()
if let prefs = NSUserDefaults(suiteName: suiteName) {
if let imageData = prefs.objectForKey(redDefaultKey) as? NSData {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.imageView.image = UIImage(data: imageData)
})
}
}
}
}
同样创建一个BlueViewController继承UIViewController,添加ImageView
import UIKit
class BlueViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
let suiteName = "paul.share.extension"
let blueDefaultKey = "BlueColorImage"
//将图片保存在NSUserDefaults中
override func viewDidLoad() {
super.viewDidLoad()
if let prefs = NSUserDefaults(suiteName: suiteName) {
if let imageData = prefs.objectForKey(blueDefaultKey) as? NSData {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.imageView.image = UIImage(data: imageData)
})
}
}
}
}
写得太水了!