0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【SwiftUI】画像をインスタグラムにシェアする

Posted at

はじめに

インスタグラムへのシェア機能を作成する方法を学んだので記録しておきます。

実装

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開発者アカウントが必要らしいです。
今回の方法は開発者アカウントなしでできます!

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?