はじめに
インスタグラムへのシェア機能を作成する方法を学んだので記録しておきます。
実装
import UIKit
public final class ImageDownloadManager: NSObject {
private var completion: (_ error: Error?) -> Void = { _ in }
public func save(image: UIImage, completion: @escaping (_ error: Error?) -> Void) {
self.completion = completion
if let data = image.pngData(), let png = UIImage(data: data) {
UIImageWriteToSavedPhotosAlbum(png, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
}
@objc
private func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
completion(error)
}
}
import Photos
import UIKit
public final class InstagramShareManager {
public init() {}
public func share() {
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
let fetchResult = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fetchOptions)
if fetchResult.firstObject != nil {
guard let lastAsset = fetchResult.lastObject,
let urlScheme = URL(string: "instagram://library?LocalIdentifier=\(lastAsset.localIdentifier)")
else {
return
}
UIApplication.shared.open(urlScheme)
}
}
}
使い方
import SwiftUI
struct ContentView: View {
private let imageDownloadManager = ImageDownloadManager()
private let instagramShareManager = InstagramShareManager()
var body: some View {
Button {
imageDownloadManager.save(image: UIImage(named: "sample")!) { error in
if let error {
print(error.localizedDescription)
} else {
instagramShareManager.share()
}
}
} label: {
Text("シェア")
}
}
}
おわり
もっといいシェアの方法があったのですが、Facebook開発者アカウントが必要らしいです。
今回の方法は開発者アカウントなしでできます!