Search code examples
iosswiftswiftuiinstagraminstagram-api

SwiftUI Share Instagram Post


I'm trying to share a post from Instagram with swiftui, but it didn't work, I didn't have any problems while sharing a story, but the post screen doesn't open when sharing a post.

// plist

<key>LSApplicationQueriesSchemes</key>
    <array>
        <string>instagram</string>
        <string>instagram-stories</string>
    </array>

Solution

  • The below code worked for me.

     Button {
                        if post.post_type !=  PostType.mp4.rawValue {
                         
                            let imagedData = NSData(contentsOf: imageURL)!
                            InstagramManager.instance.postImage(image: UIImage(data: imagedData as Data)!) { success in
                                print("insgram shared success =  \(success)")
                            }
                        } else {
    
                                let videoData = NSData(contentsOf: videoUrl!)
                                
                                InstagramManager.instance.postVideoToInstagramFeed(videoData: videoData!)
    

    }

    import SwiftUI
    import Photos
    
    final class InstagramManager : NSObject {
        
        public static let instance = InstagramManager()
        
        func postImage(image: UIImage, result:((Bool)->Void)? = nil) {
            guard let instagramURL = NSURL(string: "instagram://app") else {
                if let result = result {
                    result(false)
                }
                return
            }
            
            // let image = image.scaleImageWithAspectToWidth(640)
            
            do {
                try PHPhotoLibrary.shared().performChangesAndWait {
                    let request = PHAssetChangeRequest.creationRequestForAsset(from: image)
                    
                    let assetID = request.placeholderForCreatedAsset?.localIdentifier ?? ""
                    let shareURL = "instagram://library?LocalIdentifier=" + assetID
                    
                    if UIApplication.shared.canOpenURL(instagramURL as URL) {
                        if let urlForRedirect = NSURL(string: shareURL) {
                            UIApplication.shared.open(URL(string: "\(urlForRedirect)")!)
                        }
                    }
                }
            } catch {
                if let result = result {
                    result(false)
                }
            }
        }
        
        func postVideoToInstagramFeed(videoData: NSData) {
            
            getLibraryPermissionIfNecessary { granted in
                
                guard granted else { return }
            }
            
            PHPhotoLibrary.shared().performChanges({
    
                let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0];
                let filePath = "\(documentsPath)/\(Date().description).mp4"
                
                videoData.write(toFile: filePath, atomically: true)
                PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: filePath))
            },
            completionHandler: { success, error in
                
                if success {
                    
                    let fetchOptions = PHFetchOptions()
                    
                    fetchOptions.sortDescriptors = [NSSortDescriptor(key: "modificationDate", ascending: false)]
                    
                    let fetchResult = PHAsset.fetchAssets(with: .video, options: fetchOptions)
                    
                    if let lastAsset = fetchResult.firstObject {
                        
                        let localIdentifier = lastAsset.localIdentifier
                        let urlFeed = "instagram://library?LocalIdentifier=" + localIdentifier
                        
                        guard
                            let url = URL(string: urlFeed)
                        else {
                            
                            print("Could not open url")
                            return
                        }
                        DispatchQueue.main.async {
                            
                            if UIApplication.shared.canOpenURL(url) {
                                
                                if #available(iOS 10.0, *) {
                                    
                                    UIApplication.shared.open(url, options: [:], completionHandler: { (success) in
                                        print("Sucess")
                                    })
                                }
                                else {
                                    
                                    UIApplication.shared.openURL(url)
                                    print("Sucess")
                                }
                            }
                            else {
                                
                                print("Instagram not found")
                            }
                        }
                    }
                }
                else if let error = error {
                    
                    print(error.localizedDescription)
                }
                else {
                    
                    print("Could not save the video")
                }
            })
        }
    
        func getLibraryPermissionIfNecessary(completionHandler: @escaping  (Bool) -> Void) {
            
            guard PHPhotoLibrary.authorizationStatus() != .authorized else {
                completionHandler(true)
                return
            }
            
            PHPhotoLibrary.requestAuthorization { status in
                completionHandler(status == .authorized)
            }
        }
    }
    
    import UIKit
    
    extension UIImage {
        // MARK: - UIImage+Resize
        
        func scaleImageWithAspectToWidth(_ toWidth:CGFloat) -> UIImage {
            let oldWidth:CGFloat = size.width
            let scaleFactor:CGFloat = toWidth / oldWidth
            
            let newHeight = self.size.height * scaleFactor
            let newWidth = oldWidth * scaleFactor;
            
            UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
            draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return newImage!
        }
    }