Send Image and Text With Whatsapp - ios

I need to send an image from my app with a text, I know how to send just an image or just a text, but I don't know how to combine both of them.
Just an Image:
let image = UIImage(named: "Image") // replace that with your UIImage
let filename = "myimage.wai"
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, false)[0] as! NSString
let destinationPath = documentsPath.stringByAppendingString("/" + filename).stringByExpandingTildeInPath
UIImagePNGRepresentation(image).writeToFile(destinationPath, atomically: false)
let fileUrl = NSURL(fileURLWithPath: destinationPath)! as NSURL
documentController = UIDocumentInteractionController(URL: fileUrl)
documentController.delegate = self
documentController.UTI = "net.whatsapp.image"
documentController.presentOpenInMenuFromRect(CGRectZero, inView: self.view, animated: false)
Just a text:
var whatsappURL = NSURL(string: "whatsapp://send?text=hello,%20world")
if UIApplication.sharedApplication().canOpenURL(whatsappURL!) {
UIApplication.sharedApplication().openURL(whatsappURL!)
}
How can I send an image with a text?
EDIT #1
I found a code that share an image with text to whatsapp but it's in java, can you translate it to swift?
Intent whatsappIntent = new Intent(android.content.Intent.ACTION_SEND);
whatsappIntent.setType("image/*");
whatsappIntent.putExtra(Intent.EXTRA_TEXT, "Hello World");
whatsappIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + file)); //add image path
startActivity(Intent.createChooser(share, "Share image using"));
try {
activity.startActivity(whatsappIntent);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(activity, "Whatsapp have not been installed.", Toast.LENGTH_SHORT).show();
}

You can post Image or Text on WhatsApp. However you can't post both at a time as whatsapp does not provide any API that you can add caption and post image with text.
Now there is an api available for interacting with WhatsApp:
http://www.whatsapp.com/faq/en/iphone/23559013
Also Find below helpful answer:
You can use the UIDocumentInteractionController as mentioned in the 2nd answer to this question as of August 4, 2014: Share image/text through WhatsApp in an iOS app
Hope this will help.

A version of your share image code for swift 3:
let image = myUIImageVariable
let filename = "myimage.wai"
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, false)[0] as NSString
var destinationPath = documentsPath.appending("/" + filename) as NSString
destinationPath = destinationPath.expandingTildeInPath as NSString
let fileUrl = NSURL(fileURLWithPath: destinationPath as String) as NSURL
do{
try UIImagePNGRepresentation(image!)?.write(to: fileUrl as URL, options: Data.WritingOptions.atomic)
}
catch {}
let documentController = UIDocumentInteractionController(url: fileUrl as URL)
documentController.delegate = self
documentController.uti = "net.whatsapp.image"
documentController.presentOpenInMenu(from: CGRect.zero, in: self.view, animated: false)
Still does not seem work even for just sharing an image, but may save someone's time

Related

I am trying to upload file to firebase which is pdf in swift but getting following error [duplicate]

I need url filepath be a URL (NSURL in old versions of Swift). I have this:
let paths = NSSearchPathForDirectoriesInDomains(
.documentDirectory, .userDomainMask, true)
// NSString *documentsDirectory = [paths objectAtIndex:0];
let documentsDirectory = paths[0] as String
var filePath:String? = nil
var fileNamePostfix = 0
repeat {
filePath =
"\(documentsDirectory)/\(dateTimePrefix)-\(fileNamePostfix).mp4"
fileNamePostfix += 1
} while (FileManager.default.fileExists(atPath: filePath))
I need to convert this to URL for use in self.fileOutput.startRecording(to: <#outputFileURL: URL?#>, recordingDelegate: <#AVCaptureFileOutputRecordingDelegate?#>) method.
I tried filePath as? URL() but it isn't correct.
you need to do:
let fileUrl = URL(string: filePath)
or
let fileUrl = URL(fileURLWithPath: filePath)
depending on your needs. See URL docs
Before Swift 3, URL was called NSURL.
In swift 3 use:
let url = URL(string: "Whatever url you have(eg: https://google.com)")
in swift 4 to convert to url use URL
let fileUrl = URL.init(fileURLWithPath: filePath)
or
let fileUrl = URL(fileURLWithPath: filePath)
In Swift3:
let fileUrl = Foundation.URL(string: filePath)
To Convert file path in String to NSURL, observe the following code
var filePathUrl = NSURL.fileURLWithPath(path)

UIDocumentInteractionController show only Instagram in the application

I am trying to share photo from my iOS app to instagram app using UIDocumentInteractionController and I want to show only instagram app in popover. As instagram describe here it's possible but it not works for me, I don't know what I am missing.
Below is screenshot of instagram, that confirms it's possible.
Below is the code I am using for this.
#IBAction func sharePhoto(btn: UIButton) {
let photoBundlePath = Bundle.main.url(forResource: "Photo", withExtension: ".png")
do {
let data = try Data(contentsOf: photoBundlePath!)
let fileSavedPath = saveFile(data: data, name: "photo", fileExtension: ".igo")
let instagramUrl = URL(string: "instagram://app")
if UIApplication.shared.canOpenURL(instagramUrl!) {
ic = UIDocumentInteractionController(url: fileSavedPath)
ic.delegate = self
ic.uti = "com.instagram.exclusivegram"
ic.presentOptionsMenu(from: btn.frame, in: self.view, animated: true)
ic.annotation = ["InstagramCaption" : "Testing"]
} else {
print("Instagram is not present in your device")
}
} catch {
print(error)
}
}
func saveFile(data: Data, name: String, fileExtension: String) -> URL {
let fileManager = FileManager.default
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentDirectory = paths[0]
let fullPath = documentDirectory + "/" + name + fileExtension
fileManager.createFile(atPath: fullPath, contents: data, attributes: nil)
return URL(fileURLWithPath: fullPath)
}
One more thing here is why Instagram is shown with text "Copy to" as one can see in below image.

UNNotificationAttachment set image URL to Caches directory

I have Image cache mechanism in my app. I also need to show local notifications with images. I have a problem. When I try to set UNNotificationAttachment with an image, I get an image from my cache or, if an image doesn't exist, I download it and cache. Then I build a URL to Caches directory, but when I pass this URL to UNNotificationAttachment, I get an error: NSLocalizedDescription=Invalid attachment file URL. What do I make wrong?
if let diskUrlString = UIImageView.sharedImageCache.diskUrlForImageUrl(imageUrl) {
if let diskUrl = URL(string: diskUrlString) {
do {
res = try UNNotificationAttachment(identifier: imageUrlString, url: diskUrl, options: nil)
} catch (let error) {
print("error", error)
// Invalid attachment file URL
}
}
}
func diskUrlForImageUrl(_ imageUrl: URL) -> String? {
let urlRequest = URLRequest(url: imageUrl)
return ImageCache.cacheDirectory.appending("/\(ImageCache.imageCacheKeyFromURLRequest(urlRequest))")
}
static fileprivate var cacheDirectory: String = { () -> String in
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
let res = documentsDirectory.appending("/scAvatars")
let isExist = FileManager.default.fileExists(atPath: res, isDirectory: nil)
if !isExist {
try? FileManager.default.createDirectory(atPath: res, withIntermediateDirectories: true, attributes: nil)
}
return res
}()
I have found that if I add a prefix file:///private to diskUrlString, then URL builds like expected. But I didn't still understand, how to build the url without hardcoding this prefix. So now I can use both cache and UNNotificationAttachment!
The problem here is that you are using a path, not a URL. A path is a string, like "/var/log/foo.log". A URL is semantically more complex than a path. You need a URL that describes the location of the image file on the device file system.
Build a properly constructed URL to the image file and the attachment may work. The attachment may also need a type identifier hint to tell iOS what kind of data is in the file.
You do not have to use urls. You can use image data with UNNotificationAttachment.
Here is a sample code.
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
let imageURL = URL(fileURLWithPath: paths.first!).appendingPathComponent("\(fileName).jpg")
let image = UIImage(contentsOfFile: imageURL.path)
let imageData = image?.pngData()
if let unwrappedImageData = imageData, let attachement = try? UNNotificationAttachment(data: unwrappedImageData, options: nil) {
content.attachments = [attachement]
}

UIImage from path or filename in Swift 3

i have a bunch of images in my App's Documents Directory. i want to load one of them in an UIImage that i have in my view. this is what i do:
myImage.image = UIImage(named: "image.jpg") // the file exist but this returns nil
I also tried to init the image using:
myImage.image = UIImage(contentsOfFile: imagePath) //this also doesn't work but the path i got starts (at least in the sim) with file://
Anyone can suggest something? I'm kinda a noob in iOS programming.
Thanks
EDIT:
imagePath comes from:
func getImgPath(name: String) -> String
{
let documentsDirectory = self.getDocumentsDirectory()
let fullpath = documentsDirectory.appendingPathComponent(name)
return fullpath.absoluteString
}
This might help
let documentDirectory = FileManager.SearchPathDirectory.documentDirectory
let userDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(documentDirectory, userDomainMask, true)
if let dirPath = paths.first
{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("name.png")
let image = UIImage(contentsOfFile: imageURL.path)
// Do whatever you want with the image
}
Try adding your images under Assets.xcassets. Then you'll be able to reference your image by:
UIImage(named: 'yourImageName')
You can conveniently add images with various size settings.
You can get the path of the image as fowllows:
let imagePath = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("image.jpg")
If this doesn't work, check if your file name is correct.
I understand that if you are downloading images from internet means, you need to convert the URL to UIImage
if let url = URL(string: "your url") {
let data = try? Data(contentsOf: url)
if let imageData = data {
if let image = UIImage(data: imageData) {
imageView.image = image
}
}
}
If i understand your question correct, this will be the answer.

Get image from local URL (iOS)

I am getting a photo's URL using requestContentEditingInput using the PHLibrary
asset.requestContentEditingInput(with: PHContentEditingInputRequestOptions()) { (input, _) in
let url = input?.fullSizeImageURL
}
This URL prints: file:///Users/josh/Library/Developer/CoreSimulator/Devices/EE65D986-55E7-414C-A73E-D1C96FF17004/data/Media/DCIM/100APPLE/IMG_0005.JPG.
How do I retrieve this image? I've tried the following but it does not return anything:
var fileLocation = "file:///Users/josh/Library/Developer/CoreSimulator/Devices/EE65D986-55E7-414C-A73E-D1C96FF17004/data/Media/DCIM/100APPLE/IMG_0005.JPG"
let url = URL(string: fileLocation)
let asset = PHAsset.fetchAssets(withALAssetURLs: [url!], options: nil)
if let result = asset.firstObject {
//asset.firstObject does not exist
}
apparently apple will not allow the developer to access any and every photo in the user's photo library even after they have accepted photos usage. If you are using an image that hasnt been picked from the imagePicker, (i.e. choosing last image in library), you have to store the image in the document directory before you can use the document directory URL. I guess this prevents people hacking into others photo library
//Storing the image (in my case, when selecting last photo NOT via imagePicker)
let fileManager = FileManager.default
let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("image01.jpg")
let imageData = UIImageJPEGRepresentation(image!, 1.0)
fileManager.createFile(atPath: paths as String, contents: imageData, attributes: nil)
//Retrieving the image
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first {
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("image01.jpg")
if let imageRetrieved = UIImage(contentsOfFile: imageURL.path) {
//do whatever you want with this image
print(imageRetrieved)
}
}

Resources