はじめに
今回はアプリからインスタグラムのフィードへのシェア導線をつける実装です。詳しくはこちらに書いてあります👨💻
インスタグラムに遷移できるようにする
まずは、アプリからインスタグラムの Custom URL Scheme が利用できるように info.plist の LSApplicationQueriesSchemes
にinstagram://
を追加していきましょう。
画像を保存して LocalIdentifier を取得する
.swift
func saveImage() {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
@objc private func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
let fetchOptions: PHFetchOptions = 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 else {
return
}
let localIdentifier = lastAsset.localIdentifier
}
}
LocalIdentifier を使って Custom URL Scheme でインスタグラムに遷移する
@objc private func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
let fetchOptions: PHFetchOptions = 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
}
if UIApplication.shared.canOpenURL(urlScheme) {
UIApplication.shared.open(urlScheme)
}
}
}