Get filename UIImagePickerController in swift - ios

How do you get the filename of the picture taken from the camera with swift? I need the filename because I want to get the path and send it to the web server.
let path = NSBundle.mainBundle().pathForResource("imageName", ofType: "jpg") as String
Thanks.

Please allow me to sort your question and offer different alternatives:
When you take pictures with an iOS device by using the UIImagePickerController or any other available controller, the image is usually saved in a UIImage object and not necessary to the bundle documents folder in the app, unless you decide to do it in the code for further display.
Regarding uploading the image to a web server, it depends on the destination server requirements, therefore, you should check what are the methods available for you to upload the image to that server.
I'm familiar with few options as follow:
1) The destination server requires to deliver the image in multipart/form-data, then you should convert your UIImage to NSData by using one to the two available methods UIImageJPEGRepresentation or UIImagePNGRepresentation depending in which format you are required to send. I suggest you check how to build the call to the destination server method (there are several post in StackOverflow about it)
2) Server requires to deliver the image in base64EncodedString mode, then you need to convert your image as in the following example:
let string: String = "data:image/png;base64," + (UIImagePNGRepresentation(image!)?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength))!
3)The destination server requires a path (meaning they don't store the image): you should first save the picture in an accessible path in the web (not inside the iOS device) by probably using one of the 2 methods I just described above and then, upload the image path you get from the place you uploaded the picture to the destination server.
I hope I succeeded to help you with my answer :-)

Related

Swift, image from URL returns nil due to corrupted file type hiding as JPG

I'm experiencing a large issue right now with XCode and just MacOS/iOS in general.
For background, the website application framework I'm using is laravel and the image editor I use to crop profile images is called image intervention, a quite popular extension for laravel.
To skip straight into it- I'm creating a basic companion application for my website, which, like pretty much all other websites, stores images on the server. This can be reached with the www.mywebsite.com/storage/ base URL, with the addition of the file name on the end. There is a bit more to it, but none of that is the issue.
I've been using it many times already, as there are multiple folders for different image relationships. One folder, lets just call it postimages (so link is now www.mywebsite.com/storage/postimages), returns images with no issue, and I've been using it multiple times up to this point. The code I use in swift to return the different images is as follows (in my specific views)
func getPic(urlLink: String)-> Image? {
let baseURL = "https://www.mywebsite.com/storage"
let url = URL(string: baseURL + urlLink)
let data = try? Data(contentsOf: url!)
let image = UIImage(data: data!)
let image2 = Image(uiImage: (image ?? nil)!)
return image2
}
So this might be badly written or whatnot, but that's definitely not the source of any issue, so approach it as you wish. Anyways, again, I've used this function in multiple views to retrieve multiple different images from different folders on the storage endpoint.
The issue just came up when trying to retrieve images from a different endpoint, specifically my /profileimages endpoint. Up until now, as I've stated, this function has never had an issue. Now, when I try to use it to get profile images, it crashes the app with the error
"Unexpectedly found nil while unwrapping an Optional value"
around the line where it is let data = try? Data(contentsOf: url!).
Now this gave me much grief because the URL (when hovered) showed the
correct URL link, and when I entered them into the browser it returned
the image in question. So why is the image somehow returning nil? I
don't know.
To add to the mystery, I've been trying to work around the issue, by downloading the default profile image and just changing the function to return the default image if there was no data at the URL (even though there should be, 100% of the time).
When I tried to download the default profile picture, by using the https://www.mywebsite.com/storage/profileimages/blank.jpg link, I tried adding it to XCode as an asset and it had a big red exclamation point over it. Trying to open it with preview gave me the error "The file "blank.jpg" could not be opened. It may be damaged or use a file format the Preview doesn't recognize." This is surprising because on my Windows computer, trying to do the same thing has no issue at all.
My suspicion is that because I used the extension to crop and fit the profile images to a square size, somehow in that process of saving it, image intervention corrupted the file, and while Windows recognizes it as JPEG, Swift does not.
I ask any of those who are more experienced with image manipulation please help me understand this, obviously displaying user's profile pictures is vital to creation of a website mobile companion application, and right now I can't do anything besides basic text tabviews without this working as intended.
I'm going to post my own answer as I've been able to solve the mystery. The first problem was the default image was, indeed, corrupted. I made a new one with GIMP and have been using that one instead. Why Windows could still open it and MacOS couldn't is beyond me, perhaps they have stricter guidelines for what constitutes a JPG file and therefore the file sneaks past Windows but not Mac, whatever the issue, obviously replacing the file solved my problem. The second issue was returning nil, which I found out was because I wasn't percent encoding the URL link. Some users post pictures with spaces in it, so I needed to add percent encoding in order for it to work (for some reason). Both of those solutions combined has removed the entire problem I was facing and I no longer have pictures returning nil.
I am facing same issue but I found solution, The image is in webp format, which is specially designed by google for chrome. iOS wont support webp.

iOS store image in photos and save its path in string in objective c

I am using TUC Library to store image in a custom named album in photos
but i also need to save the path of that stored image on successful creation to display on chat interface, code I am using is as following:
import "UIImage+TUCAssetsHelper.h"
[image tuc_saveToAlbumWithAlbumName:#"SUPImages"];
//[image tuc_saveToAlbumWithAlbumName:#"any album name here"];
[image tuc_saveToAlbumWithAlbumName:#"SUPImages" success:^{
NSLog(#"save to custom name album: success!");
} failure:^(TUCAssetsHelperAuthorizationStatus status) {
NSLog(#"save to custom name album: Denied!");
}];
This is not how it works, not even in theory.
You must treat your photos library much like a remote server. You need to fetch images and display them as they are on library else you are going to have a bad time. For instance what do you expect it will happen if user deletes the image from photos library?
Anyway you need to request images and never save a file path nor URL even if you get it. You may not do that even for resource or documents directory of your own application because the base path may change (migrating to new iPhone). In case of your own file system you must save a suffix of path only so you have libraryDirectory()/myFiles/mySavedFileName. Then there is iCloud which I will not even go into.
So in case of matching images in photos library you should try to do the same as if the image was on server which means you will need to match it by some ID. Check if you can find unique identifiers for images in your photos library and save/request them. Naturally if you are going down that hole I suggest you to detach yourself from any open sources like the one you mentioned.
On the other side I would suggest you not to save images into photo library in the first place. If you do save them there also save/cache them in your application documents or library directory. Then use these local images in your application. Again make sure not to save full paths but just relative ones or you will have problems again.

How should I upload text with images Swift

I am tryin got upload a document/textView with images to my server...
Now I am trying to figure out what would be the best way:
1) You can add the images 1 by 1 to UITextView and lower the quality and upload the whole textView NSAtributedString as a NSData file or a .txt file, and then decode it when downloading.
2) While adding the images to the UITextView I upload them to the server and store a URL link to the images in the UITextView in the same place of the image, and before upload the text with the url's I convert that all to HTML and then display that in a UIWebView.
Now first option seems to be the easiest to setup, but not neccessarily the quickiest, as the final file you upload could be 2-10 mb with roughly 5-7 images with a basic quality....
Now the second option is done in app's like WordPress, and looking at they're code on github Github WordPress Keyboard they convert it differently to html using "libxml2" and store the url for the image when adding it....
And this option seems to be alot quicker I would of thought...
Now I think the second option would be the best, but I am pretty sure it can be done without using the amount of code wordpress use.
Is there a way of changing the url of an image when adding it as NSTextAttachment? Because when you convert NSAttributedText to html, the image just gets the local link to the file, and the name of the file is just "attachment"..
Now If anyone could give me some advice or better options that would be great!
Many thanks to anyone that spares some time to read this!
Create an image upload service which accept image and url as argument. Then you can generate those image url before sending them to image server and replace those local url with the generated image url.
Edit:
Maybe you can store the location of those images and remove them from the NSattributedstring first and replace with <img src = "url"> before converting it to "HTML".
But I would suggest you using one of those HTML Parser such as KANNA.

Modifying JPEG Metadata without Recompressing Image in iOS

I'm trying to use
CGImageSourceCreateWithData
CGImageDestinationCreateWithData
and then
CGImageDestinationAddImageFromSource
but this discards any thumbnails or other embedded information in the original file. What I want to do is read in the file, alter its metadata, and write it out with the alterations only. But I'll settle for reading everything out of it, and putting it back again. Right now a 1.2MB image file gets converted to a 437kB file with the loss of additional data.
Is there something other than CGImage I can use? Can this even be done with the iOS API?
The problem you face is that the structure of the metadata depends upon the specific JPEG file format you are using.
You need to look at CGImageProperties. You're going to have to make sure the properties for your specific file format get copied as well.
What I was looking for was a read-modify-write operation for image files that allowed changes but otherwise maintained unaltered data. I've determined through research and testing that this is not possible in iOS. The closest mechanism available is CGImage processing, but this only allows you to read selected information from a source image (such as image, thumbnail, properties), and then use some of that information (image, properties) to create a new destination file. There's no way to include a thumbnail in the new destination file, and no way to get around recompressing the image.
As of iOS 7 you can use CGImageDestinationCopyImageSource "to modify EXIF and other image metadata in JPEG, PNG, PSD, and TIFF files without recompressing the image data"
https://developer.apple.com/library/archive/qa/qa1895/_index.html

Is there really no way to retrieve the original filename of a photo from the photo library ?

I found some interesting topics, such as :
- How to get a photo's original filename in iOS?
or :
- Retrieving a filename for an ALAsset
but it says that you can read the local filename of the picture, but not the original name from the source image.
Indeed, on ios, the pictures are renamed to :
/var/mobile/Media/DCIM/XXXAPPLE/IMG_XXXX.JPG ou .PNG
but when I sync my phone, itunes knows which pictures are already synced, so there must be a link between the original filename and the new ?
Pure speculation: it's possible that iTunes could know both the original filename and the "synched" filename that is used on the iOS device, while iOS knows only the local name, which would make it impossible to retrieve the original filename on the iOS device.
iOS tries to be different than many OSes in that it does not push the abstraction of content into filesystem (files, filenames, folders and so on). In some situations it might be better to continue on this path.

Resources