CKAsset (NSData) to UIWebView to share with ActivityViewController - ios

I have PDF Files as CKAssets, which are called and presented in a UIWebView without issue. I have managed to manipulate the code so as the CKAsset will present in a ActivityViewController, but this is within the func method and I wish to assign this part to an Action button. My question is how can I call a few lines within a function? or have sufficient references outside the func to make the action button work?
Here is the func code -
func queryRecord() {
let container = CKContainer.default()
let publicDatabase = container.publicCloudDatabase
let predicate = NSPredicate(format: "recordID = %#", CKRecordID(recordName : documentID))
let query = CKQuery(recordType: "Documents", predicate: predicate)
publicDatabase.perform(query, inZoneWith: nil, completionHandler: ({results, error in
if (error != nil) {
DispatchQueue.main.async() {
self.notifyUser("Cloud Access Error", message: error!.localizedDescription)
}
} else {
if results!.count > 0 {
let record = results![0]
print(record)
DispatchQueue.main.async() {
let docTitle = record.object(forKey: "documentName") as! String
self.title = "\(docTitle)"
let docType = record.object(forKey: "documentType") as! String
if docType == "PDF" || docType == "pdf" {
if let asset1 = record.object(forKey: "documentFile") as? CKAsset {
let doc1Data : NSData? = NSData(contentsOf:asset1.fileURL)
self.docWebView.load(doc1Data! as Data, mimeType: "application/pdf", textEncodingName: "UTF-8", baseURL: NSURL() as URL)
let filenameURL = [(asset1.fileURL)]
let activityController = UIActivityViewController(activityItems: filenameURL, applicationActivities: nil)
self.present(activityController, animated: true, completion: nil)
}
} else {
I have tried to reference filenameURL outside the code, but it does not recognise that filenameURL is no member of the class.

I figured it out (I think). Here goes -
I changed
let filenameURL = [(asset1.fileURL)]
to
self.filenameURL = [(asset1.fileURL)]
then added
var filenameURL : Any?
to the ViewController Class. Which allowed me to add the relevant code to the actionButton -
#IBAction func activityVCButton(_ sender: UIBarButtonItem) {
let activityController = UIActivityViewController(activityItems: (filenameURL as? [Any])!, applicationActivities: nil)
self.present(activityController, animated: true, completion: nil)
}
I think the key, which I seemed to be missing was the Any?, but I am happy to be corrected if there was something more fundamental I was missing.

Related

firestore not accepting my video url to be uploaded to storage Xcode/iOS

hey guys currently working on a messaging app to send videos to users, I know its been done a million times. but I am running into a strange error that I can't figure out. I am trying to use firebase Firestore, and I am successful in uploading the image to firestore through an image picker, however when I try to upload a selected video I get an error that says
2021-05-17 18:11:32.597321-0500 scyneApp[3287:201297] Failed to issue sandbox extension for file file:///private/var/mobile/Containers/Data/PluginKitPlugin/3B9F83AF-638C-4F48-ADD8-5A95742E5A59/tmp/trim.68A0ABAC-279D-4A54-8896-132B35A3B24F.MOV, errno = 1
here is my code
actionSheet.addAction(UIAlertAction(title: "choose video from library", style: .default, handler: {[weak self] _ in
let picker = UIImagePickerController()
picker.sourceType = .photoLibrary
picker.delegate = self
picker.mediaTypes = ["public.movie"]
picker.allowsEditing = true
picker.videoQuality = .typeMedium
self?.present(picker, animated: true, completion: nil)
//
extension ChatViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true, completion: nil)
guard let mediaType = info[UIImagePickerController.InfoKey.mediaType] as? String else {return}
print(mediaType)
guard let convoId = self.conversationId else {
print("mayo")
return}
if let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
//image upload code which works fine
} else if let videoUrl = info[UIImagePickerController.InfoKey.mediaURL] as? URL {
guard let filename = createFilename() else {
return}
print(videoUrl)
//upload video
StorageManager.shared.uploadMessageVideo(with: videoUrl, convoId: convoId, filename: filename, completion: { [weak self] url in
print("video uploaded")
guard let strongSelf = self else {return}
guard let videoUrl = url else {return}
guard videoUrl != nil else {return}
guard let username = UserDefaults.standard.string(forKey: "username") else {return}
guard let messageId = strongSelf.createMessageID() else {return}
guard let selfSend = strongSelf.selfSender else {return}
guard let placeHolder = UIImage(systemName: "video") else {return}
let media = Media(url: videoUrl, image: nil, placeholderImage: placeHolder, size: .zero)
let message = Message(sender: selfSend, messageId: messageId, sentDate: Date(), kind: .video(media))
DatabaseManager.shared.sendMessage(to: convoId, newMessage: message, name: username, otherUserUsername: strongSelf.otherUserName, otherUserEmail: strongSelf.otherUserEmail, completion: {
success in
if success {
print("success")
} else {
print("failed to send message")
}
})
})
}
}
}
//
public func uploadMessageVideo(with url: URL, convoId: String, filename: String, completion: #escaping (URL?) -> Void) {
let ref = storage.child("\(convoId)/\(filename).mov")
ref.putFile(from: url, metadata: nil, completion: {
_, error in
print(error)
guard error == nil else {
print("there is an error")
return}
ref.downloadURL { url, _ in
completion(url)
}
})
}

Sending email with multiple attachments (Swift)

I am wanting to send an email with multiple excel attachments.
The below code has func to create each file and save in a created user directory.
The files are saved fine.
The email is generated and sends fine.
My one issue that I cannot solve is: It is attaching TWO copies of each file, causing the email to have two sets of attached data.
The issue seems to be in the func configuredMailComposeViewController.
Can someone please help me fix the code so it will only send a single set of files?
class ExportToExcel: UIViewController, MFMailComposeViewControllerDelegate, UINavigationControllerDelegate {
var taskArr = [Export]()
var task: Export!
var noteID:Int = -1
var contactID:Int = -1
var companyID:Int = -1
let mailComposer = MFMailComposeViewController()
var fileNameNote = String()
var fileNameCompany = String()
var fileNameWC = String()
var fileNameBldg = String()
var fileNameCurrent = String()
var fileNameLoss = String()
fileprivate var contactDetails: ContactModel = ContactModel()
fileprivate var companyDetails: ContactModel = ContactModel()
fileprivate var quickNoteDetails: QuickNoteModel = QuickNoteModel()
fileprivate var bizDetails: BizDetailsModel = BizDetailsModel()
fileprivate var imageNames: Array<PhotoModel> = [PhotoModel]()
override func viewDidLoad() {
super.viewDidLoad()
// creating the "MeetingNotes" directory
self.createNewDir()
mailComposer.mailComposeDelegate = self
mailComposer.delegate = self
self.sendEmailButton()
}
func setFileLocation(_ fileName: String) -> URL {
let filemgr = FileManager.default
let dirPaths = filemgr.urls(for: .documentDirectory, in: .userDomainMask)
let docsURL = dirPaths[0].appendingPathComponent("MeetingNotes")
let path = docsURL.appendingPathComponent(fileName)
return path
}
func createNewDir() {
let filemgr = FileManager.default
let dirPaths = filemgr.urls(for: .documentDirectory, in: .userDomainMask)
let docsURL = dirPaths[0]
let newDir = docsURL.appendingPathComponent("MeetingNotes").path
do {
try filemgr.createDirectory(atPath: newDir,
withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
}
}
func createNoteCSV() -> Void {
fileNameNote = ("\(task.Company_Name)-\(task.Note_Date)-Note.xls").removeSpaces
let path = setFileLocation(fileNameNote)
var csvText = "Note Date,Note Details,Company Name,Company Phone,Contact Name,Contact Office,Contact Mobile,Contact Email,Coverages,BOP SIC,NAICS\n"
let newLine = "\(task.Note_Date),\(task.Notes.removeCommas),\(task.Company_Name),\(task.Company_Phone),\(task.Contact_Name),\(task.Contact_Office),\(task.Contact_Mobile),\(task.Contact_Email),\(task.Coverages),\(task.BOP_SIC),\(task.NAICS)"
csvText.append(newLine)
do {
try csvText.write(to: path, atomically: true, encoding: String.Encoding.utf8)
let url = path
let activityViewController = UIActivityViewController(activityItems: [url as Any] , applicationActivities: nil)
DispatchQueue.main.async {
self.present(activityViewController, animated: true, completion: nil)
}
} catch {
print("Failed to create file ")
print("\(error)")
}
}
func createBldgCSV() -> Void {
if !BuildingsArrayExport.array.isEmpty {
fileNameBldg = ("\(task.Company_Name)-\(task.Note_Date)-Bldg.xls").removeSpaces
let path = setFileLocation(fileNameBldg)
var csvText = "Note Date,Company Name,Bldg Nickname,Bldg Address, Bldg City, Bldg State, Bldg Zipcode,Deductible,Bldg Year,Office SqFt,Bldg SqFt,Floors,Roof Type,Construction Type,Bldg Type,Bldg Value,Yr Heat Replaced,Yr Wire Replaced,Yr Roof Replaced,Yr Plumbing Replaced,Pct Bldg Occupied,Pct Tenant Occupied,Pct Sprinkler,Responible for Parking lot,Alarm Type\n"
let items = BuildingsArrayExport.array
for item in items {
let address = "\(item.address1) \(item.address2)"
let newLine = "\(task.Note_Date),\(task.Company_Name),\(item.nickName),\(address.removeCommas),\(item.city.removeCommas),\(item.state),\(item.zipCode),\(item.deductible.removeCommas),\(item.buildingYr),\(item.officeSqFt),\(item.buildingSqFt),\(item.buildingStories),\(item.roofType.removeCommas),\(item.constructionType.removeCommas),\(item.buildingType.removeCommas),\(item.buildingValue.removeCommas),\(item.heatingReplaced),\(item.wiringReplaced),\(item.roofReplaced),\(item.plumbingReplaced),\(item.percentUnoccupied),\(item.percentOthersOccupied),\(item.sprinklerSystem),\(item.responsibleForParkingLot),\(item.alarmType)\n"
csvText.append(newLine)
}
do {
try csvText.write(to: path, atomically: true, encoding: String.Encoding.utf8)
let url = path
let activityViewController = UIActivityViewController(activityItems: [url as Any] , applicationActivities: nil)
DispatchQueue.main.async {
self.present(activityViewController, animated: true, completion: nil)
}
} catch {
print("Failed to create file ")
print("\(error)")
}
} else {
return
}
}
// more of the same func types, but deleted to reduce post size
func sendEmailButton() {
guard appOwnerEmail != nil else {
return
}
self.createNoteCSV()
self.createCompanyCSV()
self.createBldgCSV()
self.createWcCSV()
self.createLossCSV()
self.createCurrentCSV()
let mailComposeViewController = configuredMailComposeViewController(appOwnerEmail)
if MFMailComposeViewController.canSendMail() {
self.present(mailComposeViewController, animated: true, completion: nil)
} else {
self.showSendMailErrorAlert()
}
}
// During this function, it will post all data twice. This includes
// 2 x each xls and 2 x each image.
// The "do" portion of this func gets executed twice.
// That is the issue
func configuredMailComposeViewController(_ email: String) -> MFMailComposeViewController {
mailComposer.setSubject("\(task.Company_Name) meeting note")
mailComposer.setMessageBody("Meetings note details)", isHTML: true)
mailComposer.setToRecipients([appOwnerEmail])
mailComposer.setCcRecipients([""])
mailComposer.setBccRecipients([""])
let filemgr = FileManager.default
let dirPaths = filemgr.urls(for: .documentDirectory,
in: .userDomainMask)
do {
let fileNoteURL = setFileLocation(fileNameNote)
let attachmentNoteData = try Data(contentsOf: fileNoteURL)
mailComposer.addAttachmentData(attachmentNoteData, mimeType: "application/xls", fileName: fileNameNote)
let fileCompanyURL = setFileLocation(fileNameCompany)
let attachmentCompanyData = try Data(contentsOf: fileCompanyURL)
mailComposer.addAttachmentData(attachmentCompanyData, mimeType: "application/xls", fileName: fileNameCompany)
if !BuildingsArrayExport.array.isEmpty {
let fileBldgURL = setFileLocation(fileNameBldg)
let attachmentBldgData = try Data(contentsOf: fileBldgURL)
mailComposer.addAttachmentData(attachmentBldgData, mimeType: "application/xls", fileName: fileNameBldg)
}
if !WorkersCompArrayExport.array.isEmpty {
let fileWCURL = setFileLocation(fileNameWC)
let attachmentWCData = try Data(contentsOf: fileWCURL)
mailComposer.addAttachmentData(attachmentWCData, mimeType: "application/xls", fileName: fileNameWC)
}
if !CurrentPolicyArrayExport.array.isEmpty {
let fileCPURL = setFileLocation(fileNameCurrent)
let attachmentCPData = try Data(contentsOf: fileCPURL)
mailComposer.addAttachmentData(attachmentCPData, mimeType: "application/xls", fileName: fileNameCurrent)
}
if !LossItemsArrayExport.array.isEmpty {
let fileLossURL = setFileLocation(fileNameLoss)
let attachmentLossData = try Data(contentsOf: fileLossURL)
mailComposer.addAttachmentData(attachmentLossData, mimeType: "application/xls", fileName: fileNameLoss)
}
imageNames = AppDelegate.getUserDatabase().getPhotoList(noteID)
for imageName in imageNames {
let name = imageName.name
let imageURL = dirPaths[0].appendingPathComponent(name)
let attachmentImages = try Data(contentsOf: imageURL)
mailComposer.addAttachmentData(attachmentImages, mimeType: "application/jpg", fileName: name)
mailComposer.mailComposeDelegate = self
self.present(mailComposer, animated: true
, completion: nil)
}
if MFMailComposeViewController.canSendMail() {
self.present(mailComposer, animated: true
, completion: nil)
} else {
print("Emails not configured")
}
} catch let error {
print("We csv encountered error \(error.localizedDescription)")
}
return mailComposer
}
func showSendMailErrorAlert() {
let sendMailErrorAlert = UIAlertController(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", preferredStyle: .alert)
sendMailErrorAlert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
self.present(sendMailErrorAlert, animated: true){}
self.dismiss(animated: false, completion: nil)
}
public func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
switch result {
case .cancelled:
print("Mail cancelled")
case .saved:
AppDelegate.getUserDatabase().recordEmailSent(noteID)
print("Mail saved")
case .sent:
AppDelegate.getUserDatabase().recordEmailSent(noteID)
print("Mail sent")
case .failed:
break
#unknown default:
fatalError()
}
controller.dismiss(animated: true) {
self.dismiss(animated: true, completion: nil)
}
}
}
I found the error and it was being caused by a different viewController.
I am leaving the code up and lengthy to support someone else who may need help exporting multiple file via email.

Upload Image from the gallery into Firebase with Swift 4.2

I've got a problem regarding Firebase and the upload of pictures..
I've been tried to follow the Firebase doc but I'm not sur to do the right things ...
In my application I want to send in firebase the value of 2 textfields and 1 segmented control plus one picture which is coming from the iphone's gallery.
well my save button :
#IBAction func saveBtnWasPressed(_ sender: Any) {
//Informations from the segmented control
if isMe == false {// Si SE
acftType = "SE"
}else if isMe == true {//Si ME
acftType = "ME"
}
let ref = Database.database().reference()
let userID = Auth.auth().currentUser?.uid
let usersPlanes : NSDictionary = [ "Registration" : self.acftRegTxtField.text!,
"model": self.acftModelTxtField.text!,
"Type" : self.acftType]
if isMe == false {// Si SE
ref.child("Planes").child(userID!).child("SE").childByAutoId().setValue(usersPlanes)
}else if isMe == true {//Si ME
ref.child("Planes").child(userID!).child("ME").childByAutoId().setValue(usersPlanes)
}else{
print("Error: Impossible to find the type of aircraft...")
}
let Dpalert = UIAlertController(title: nil, message: "Your informations as been upload", preferredStyle: .alert)
Dpalert.addAction(UIAlertAction(title: "Roger", style: .cancel, handler: nil))
self.present(Dpalert, animated: true)
}
And my function to allow user to select an image from his gallery is :
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let userID = Auth.auth().currentUser?.uid
self.dismiss(animated: true, completion: nil)
if let selectedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
self.planImageView.image = selectedImage
var data = Data()
data = selectedImage.jpegData(compressionQuality: 0.75)!
}else{
print("Error : Impossible to deal with this image...")
}
let imageRef = Storage.storage().reference().child("Images").child(userID!).child(randomString(20));
let uploadPict = imageRef.putData(data, metadata: nil){ (metadata, error) in
guard let metadata = metadata else {
return
}
let size = metadata.size
imageRef.downloadURL { (url, error) in
guard let downloadURL = url else {
return
}
}
}
But nothing appears in firebase when the picture is load in the app and How can I add it in the same folder as my first 3 information send with the save button ?
I'm totally lost with all this information. How can I solve my problem ?
Thanks very much for your help !
Flyer-74
In this function
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let userID = Auth.auth().currentUser?.uid
self.dismiss(animated: true, completion: nil)
if let selectedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
self.planImageView.image = selectedImage
var data = Data()
data = selectedImage.jpegData(compressionQuality: 0.75)!
}else{
print("Error : Impossible to deal with this image...")
}
let imageRef = Storage.storage().reference().child("Images").child(userID!).child(randomString(20));
let uploadPict = imageRef.putData(data, metadata: nil){ (metadata, error) in
guard let metadata = metadata else {
return
}
let size = metadata.size
imageRef.downloadURL { (url, error) in
guard let downloadURL = url else {
return
}
}
}
Try to put an output when your putData fail
let uploadPict = imageRef.putData(data, metadata: nil){ (metadata, error) in
guard let metadata = metadata else {
print("Error with upload \(String(describing: error?.localizedDescription))")
return
}
let size = metadata.size
imageRef.downloadURL { (url, error) in
guard let downloadURL = url else {
print("Error with download URL: \(String(describing: error?.localizedDescription))")
return
}
}
Maybe it will help you to recognize the error; tell me what you got in the error

iOS Swift 3: Share Data from share extension to Host App

Hello i have implemented Share extension for my app in which picks images from gallery and send to a particular view. Now the problem is when i'm trying to save array of images(images picked from gallery)
func manageImages() {
let content = extensionContext!.inputItems[0] as! NSExtensionItem
let contentType = kUTTypeImage as String
for (index, attachment) in (content.attachments as! [NSItemProvider]).enumerated() {
if attachment.hasItemConformingToTypeIdentifier(contentType) {
attachment.loadItem(forTypeIdentifier: contentType, options: nil) { data, error in
if error == nil, let url = data as? URL {
do {
let imageData = try Data(contentsOf: url)
let image = UIImage(data: imageData)
self.selectedImages.append(image!)
if index == (content.attachments?.count)! - 1 {
self.imgCollectionView.reloadData()
UserDefaults.standard.set(self.selectedImages, forKey: "PHOTOKEY")
UserDefaults.standard.synchronize()
}
}
catch let exp {
print("GETTING ERROR \(exp.localizedDescription)")
}
} else {
print("GETTING ERROR")
let alert = UIAlertController(title: "Error", message: "Error loading image", preferredStyle: .alert)
let action = UIAlertAction(title: "Error", style: .cancel) { _ in
self.dismiss(animated: true, completion: nil)
}
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
}
}
}
}
and fetching that array in AppDelegate method
func application(_ app: UIApplication,
open url: URL,
options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
if let key = url.absoluteString.components(separatedBy: "=").last, let _ = UserDefaults.standard.array(forKey: key) {
let myVC = UIStoryboard.getViewController(storyboardName: "Main",
storyboardId: "MyViewController")
let navVC = UIStoryboard.getViewController(storyboardName: "Main",
storyboardId: "MyNavigationVC") as! UINavigationController
navVC.viewControllers.append(myVC)
self.window?.rootViewController = navVC
self.window?.makeKeyAndVisible()
return true
}
return false
}
I'm sending url let url = URL(string: "unfoldsPrintsShare://dataUrl=PHOTOKEY") and able to get PHOTOKEY
successfully but array getting nil and hence condition is false.
What should i do ?, i googled a lot but didn't find any answer
Also i'm not getting logs when i'm trying to attach extension process via debug.
P.S. : Using Xcode 8.3.3 iOS 10.3, iPhone 6 physical device
Update: Tried Via App Groups Suit Names also
let userDefaults = UserDefaults(suiteName: "group.com.company.appName")
userDefaults?.set(self.selectedImages, forKey: "PHOTOKEY")
userDefaults?.synchronize()
Still No luck
According to #Stefan Church, i tried like this
let imagesData: [Data] = []
saving image Data format into array instead of UIImage
let userDefaults = UserDefaults(suiteName: "group.com.myconmanyName.AppName")
userDefaults?.set(self?.imagesData, forKey: key)
userDefaults?.synchronize()
and it works
Thanks Stefan Church

How to share image in instagram?Swift

Sorry for the question without a code.But i didn't find anywhere to look for.
I want to share image with title in instagram? How can i do that?
Any help would be great
if you don't want to use UIDocumentInteractionController
SWIFT 5 update
import Photos
...
func postImageToInstagram(image: UIImage) {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
#objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if error != nil {
print(error)
}
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
let fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
if let lastAsset = fetchResult.firstObject as? PHAsset {
let url = URL(string: "instagram://library?LocalIdentifier=\(lastAsset.localIdentifier)")!
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url)
} else {
let alertController = UIAlertController(title: "Error", message: "Instagram is not installed", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
}
}
Swift 3.0 Version :
#IBAction func shareInstagram(_ sender: Any) {
DispatchQueue.main.async {
//Share To Instagram:
let instagramURL = URL(string: "instagram://app")
if UIApplication.shared.canOpenURL(instagramURL!) {
let imageData = UIImageJPEGRepresentation(image, 100)
let writePath = (NSTemporaryDirectory() as NSString).appendingPathComponent("instagram.igo")
do {
try imageData?.write(to: URL(fileURLWithPath: writePath), options: .atomic)
} catch {
print(error)
}
let fileURL = URL(fileURLWithPath: writePath)
self.documentController = UIDocumentInteractionController(url: fileURL)
self.documentController.delegate = self
self.documentController.uti = "com.instagram.exlusivegram"
if UIDevice.current.userInterfaceIdiom == .phone {
self.documentController.presentOpenInMenu(from: self.view.bounds, in: self.view, animated: true)
} else {
self.documentController.presentOpenInMenu(from: self.IGBarButton, animated: true)
}
} else {
print(" Instagram is not installed ")
}
}
}
class viewController: UIViewController, UIDocumentInteractionControllerDelegate {
var yourImage: UIImage?
var documentController: UIDocumentInteractionController!
func shareToInstagram() {
let instagramURL = NSURL(string: "instagram://app")
if (UIApplication.sharedApplication().canOpenURL(instagramURL!)) {
let imageData = UIImageJPEGRepresentation(yourImage!, 100)
let captionString = "caption"
let writePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent("instagram.igo")
if imageData?.writeToFile(writePath, atomically: true) == false {
return
} else {
let fileURL = NSURL(fileURLWithPath: writePath)
self.documentController = UIDocumentInteractionController(URL: fileURL)
self.documentController.delegate = self
self.documentController.UTI = "com.instagram.exlusivegram"
self.documentController.annotation = NSDictionary(object: captionString, forKey: "InstagramCaption")
self.documentController.presentOpenInMenuFromRect(self.view.frame, inView: self.view, animated: true)
}
} else {
print(" Instagram isn't installed ")
}
}
}
Now this still wont work with iOS 9, so you will have to go to your apps info.plist, add "LSApplicationQueriesSchemes" type: Array, and add the URL Scheme in this case "instagram".
Here try this code
#IBAction func shareContent(sender: UIButton) {
let image = UIImage(named: "imageName")
let objectsToShare: [AnyObject] = [image!]
let activityViewController = UIActivityViewController(
activityItems: objectsToShare,
applicationActivities: nil
)
activityViewController.popoverPresentationController?.sourceView = self.view
activityViewController.excludedActivityTypes = [
UIActivityTypeAirDrop,
UIActivityTypePostToFacebook
]
self.presentViewController(
activityViewController,
animated: true,
completion: nil
)
}

Resources