UIImage imageWithContentsOfFile: not working on real device - ios

I'm creating a tableView which contains the images from gallery picked by the user, then I take the selected imagePath to place it on an UIImageView.
To set an iOS gallery image in a UIImageView,
I'm using:
NSString *imgPath = #"/var/mobile/Media/DCIM/105APPLE/IMG_5903.JPG";//Hardcoded path just for test, image actually exists on iOS device
self.imgViewContainer.image = [UIImage imageWithContentsOfFile: imgPath];
This code which works on Simulator.
I tested on a real device and I noticed that the UIImageView is empty after execute the above code.
Is there a way to achieve this using a real device?

Due to app sandboxing, your app does not have permission to view the contents of /var/mobile/Media (or really any subdirectory of /var/). Consider the code below:
do {
let fileList = try FileManager.default.contentsOfDirectory(atPath: "/var/mobile/Media/DCIM/")
} catch {
print(error)
}
contentsOfDirectory(atPath:) with throw an error with these details:
Error Domain=NSCocoaErrorDomain Code=257 "The file “DCIM” couldn’t be opened because you don’t have permission to view it." UserInfo={NSFilePath=/var/mobile/Media/DCIM/, NSUserStringVariant=(
Folder
), NSUnderlyingError=0x170045700 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}
This example is in Swift, but the equivalent Objective-C code would have the same error.
There is no way around this (unless your are using a jailbroken device running your application as the root user). Use UIImagePickerController to ask the user for an image.

Related

iOS 14 NSItemProvider loadDataRepresentation() returns nil data for specified types

Setup:
I am using PHPickerViewController to allow the user to select photos. I've implemented the PHPickerViewControllerDelegate protocol method picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]). I am getting the itemProvider from the results array.
Problem:
I need to access the data for the selected image. There is a method on NSItemProvider called loadDataRepresentation(), which takes a type identifier string and should return the image data in its completion block.
When I call this method sometimes it returns data, sometimes it doesn't. I've tried this for the multiple registered type identifiers for each provider, and I'm seeing the same thing. Sometimes it will return JPEG data, but not HEIF, other times only HEIF, and sometimes it won't return any data at all. This is consistent in that the same photo exhibits the same result each time I try to load its data.
When there is no data I see the following error:
Upload preparation for claim D8C281B7-CCCE-4299-95BF-9355FCF340E4 completed with error: Error Domain=NSCocoaErrorDomain Code=260 "The file “7AB1AB3F-7643-45C1-9DD9-5F5642965C3A.jpeg” couldn’t be opened because there is no such file."
Is there something I need to do to the photo before attempting to load its data? Maybe I'm missing a step here? This happens for photos I took directly with my iPhone XR. I am not using iCloud Photos, all photos are on the device.
"public.image" this identifier seems to be able to get all type of photos.
example : -
loadDataRepresentation(forTypeIdentifier: "public.image")
If you're getting this error in simulator it seems like it may be an OS bug, because doing a Device > Erase All Content and Settings.. to reset the simulator fixed this for me.

Rewrite or delete existing .png file in IOS swift apllication

I would like to add the text on my .png image which exist in my swift application and REPLACE my old image with this edited image.
But when I am trying to remove old image I am getting the error message :
Error : Error Domain=NSCocoaErrorDomain Code=513 "“Background.png”
couldn’t be removed because you don’t have permission to access it."
UserInfo={NSFilePath=/var/containers/Bundle/Application/57134C17-50A5-
4709-9E3B-8013733175BA/SignatureApp.app/Background.png, NSUserStringVariant=(
Remove
), NSUnderlyingError=0x12cd8c150 {Error
Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}
Code which I am using to remove my old png file is :
let path = NSBundle.mainBundle().pathForResource("Background", ofType: "png")!
let fileManager = NSFileManager.defaultManager()
do {
try fileManager.removeItemAtPath(path)
}
catch let error as NSError {
print("Error: \(error)")
}
Can anybody give an idea how is it possible to rewrite or delete existing .png file in IOS swift aplication?
I don't believe you can do this. The image is part of your app bundle. You would need to upload a new application.
Instead you could store the image in the documents or cache directory and in your code check if that file exists and load it instead of Background.png.

Can I save files/folders in NSSearchPathDirectory.ApplicationDirectory? NSSearchPathDirectory.DocumentDirectory is not ideal for me

iOS 8.4 | Swift 2.1
When I was tried to create a new folder in NSSearchPathDirectory.ApplicationDirectory, I followed with this error on device (in simulator it did worked, though):
code:
let docuPath:NSURL = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.ApplicationDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0])
ConstantsVO.imagePath = docuPath.URLByAppendingPathComponent("imagegallery")
if !NSFileManager.defaultManager().fileExistsAtPath(ConstantsVO.imagePath.path!)
{
do
{
try NSFileManager.defaultManager().createDirectoryAtPath(ConstantsVO.imagePath.path!, withIntermediateDirectories: true, attributes: nil)
}
catch let error as NSError
{
NSLog("\(error.localizedDescription)")
}
catch
{
print("general error - \(error)", terminator: "\n")
}
}
error
2015-11-02 10:53:21.114 Elmo[218:5055] You don’t have permission to
save the file “imagegallery” in the folder “Applications”. fatal error:
'try!' expression unexpectedly raised an error: Error
Domain=NSCocoaErrorDomain Code=4 "The file “imagegallery” doesn’t
exist."
UserInfo={NSURL=file:///var/mobile/Containers/Data/Application/48D90635-0D66-44C2-81CE-F67BAFDA819A/Applications/imagegallery,
NSFilePath=/var/mobile/Containers/Data/Application/48D90635-0D66-44C2-81CE-F67BAFDA819A/Applications/imagegallery,
NSUnderlyingError=0x16e7d540 {Error Domain=NSPOSIXErrorDomain Code=2
"No such file or directory"}}: file
/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-700.0.59/src/swift/stdlib/public/core/ErrorType.swift,
line 50
However, using NSSearchPathDirectory.DocumentDirectory did worked for me and worked expectedly. But in my application, I've feature to share/import through iTunes, so I have the "Application supports iTunes file sharing" TRUE in my info.plist - this exposed NSSearchPathDirectory.DocumentDirectory in iTunes. I don't want the files/folders that I'm saving through my app to be expose to the user in iTunes. Then where should I save the files/folders yet can able to use file sharing through iTunes by exposing NSSearchPathDirectory.DocumentDirectory?
I found the answer from this post is helpful:
Path directory usable in iOS
As far as I know only these are usable on iOS:
NSDocumentDirectory is Documents/ (persistent, backed up, may
be visible in iTunes) NSLibraryDirectory is Library/
(persistent, backed up, not visibe to the user) NSCachesDirectory is
Library/Caches/ (not backed up, may be cleared by system)
Now after I'm using NSSearchPathDirectory.LibraryDirectory the I'm having no NSFileManager error on device nor the directories/files I'm storing inside NSSearchPathDirectory.LibraryDirectory are exposed to the users in iTunes sharing tab.
Great!

iPad saving audio save to local MusicDirectory

iOS 8.2
iPad a1474
inside app on IPAD, my code is
var dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
user records voice and it saves to
Optional(file:///var/mobile/Containers/Data/Application/2B2028C4-8E7D-4D7F-9FAF-EB843F506A5E/Documents/audio-2015-01-25-144545.m4a)
in Itunes/App,
have tried
MusicDirectory and SharedPublicDirectory
with either of
LocalDomainMask or DocumentDirectory
none work with error
The operation couldn’t be completed. (OSStatus error 2003334207.)
fatal error: unexpectedly found nil while unwrapping an Optional value
so what gives?
why can't app save to local MusicDirectory on the iPad??? there is nothing in the docs to indicate that this is protected area on the iPad.
no issues with iTunes or OSX, this is an iOS issue.
Under iOS8, the path that you have saved won't be the same across launches. The id you see "410AB24E-5FB0-4401-AC59-3C03D676E951" will change with each launch.
The workaround is to save the filename and not the complete path, and to recreate the URL or complete path, by getting the path to the Documents (or tmp) folder and appending the filename to it.

FILE-ACCESS Reading images previously written to NSDocumentDirectory FAILS

Having recently downloaded and installed XCode 4.3 from the App Store, I find a serious and unexpected problem when reading image-files (large JPEG files) previously stored in the application User Documents. The issue is as follows:
(i) The files derive from the user's photo-library and the UIcropped original image ( UIImagePickerControllerOriginalImage) is correctly stored to User Documents. Inspection of the User Documents folder shows the image file correctly stored. Copying this file to my user-account creates a copy that can be loaded (for example) into the Preview application or else iPhoto. The expected image is loaded by Preview and iPhoto and can be seen to be visually correct.
(ii) On attempting to read the stored file with the standard method
UIImage * image = [ UIImage imageWithContentsOfFile: file ]
method (where file is the full path-name of the stored file) the image returned is nil. nil is also returned on attempting an NSData load via
NSData * data = [ NSData dataWithContentsOfFile: file options:
NSDataReadingMappedIfSafe error: & error ];
In this case the full NSError * error object is reported as follows:
CODE= 260, DOMAIN= NSCocoaErrorDomain,
USERINFO =
{ NSFilePath = "<User Documents>/<filename>.jpeg";
NSUnderlyingError = "Error Domain=NSPOSIXErrorDomain
Code=2 \"The operation couldn't be completed. No such file or directory\"";
}
(iii) Examining the copied file in Finder shows that the "Kind" of the previousl;y written image-file is now "Document" wheras previously it was (as expected) "JPEG Image". This is the ONLY evident problem with the file.
(iv) Replacing the previous written file with an externally created JPEG image file WITH EXACTLY THE SAME NAME results in a successful loading of the file via [ UIImage imageWithContentsOfFile: file ]!
THIS LOOKS, THEREFORE, TO BE A PERMISSIONS PROBLEM RATHER THAN A JPEG-DATA PROBLEM. New with XCode 4.3 installation is the Kind= "Document" replacing the previous (and working) Kind = "JPEG Image". CAN ANYONE PLEASE THROW LIGHT ON THIS MATTER AND IF POSSIBLE ADVISE A SOLUTION? The matter is urgent & frustrating for me as it breaks a PDF design tool under urgent development!
Best Wishes,
Negative Entropy
Can you debug and "po file" from the console? I've not seen a permission problem before, so I suspect the path. Also, we have seen issues with case sensitivity (iOS is case sensitive, whereas your Simulator may not be). Need to see the full path variable contents.

Resources