Transform video file from library to NSData object, using full path to that video (in Swift) - ios

How read video file from video library on the phone if we know full path to video file, for example:
/private/var/mobile/Media/DCIM/100APPLE/IMG_0011.MOV
I tried to use that path in NSData like this:
let videoData = try NSData(contentsOfFile: "/private/var/mobile/Media/DCIM/100APPLE/IMG_0011.MOV", options: NSDataReadingOptions.DataReadingMappedIfSafe)
but I receive this error:
Error Domain=NSCocoaErrorDomain Code=257
"The file “IMG_0011.MOV” couldn’t be opened because you don’t have permission to view it."
UserInfo={NSFilePath=/private/var/mobile/Media/DCIM/100APPLE/IMG_0011.MOV,
NSUnderlyingError=0x17d88fc0 {Error Domain=NSPOSIXErrorDomain Code=1
"Operation not permitted"}}
Reading (loading) video file from folder (path) in the aplication works fine, but reading from path that is not in the application folder (like path above) does not work.
So, my question is: how read (get) video file from phone's video library (using full video path) and transform to NSData object, but without saving any data to the disc (using RAM only) during that process?

Related

Unable to fetch data from URL of video Asset from Photos framework

I'm stuck with this error.
Error Domain=NSCocoaErrorDomain Code=257 "The file “IMG_4156.MP4”
couldn’t be opened because you don’t have permission to view it."
UserInfo={NSFilePath=/var/mobile/Media/DCIM/104APPLE/IMG_4156.MP4,
NSUnderlyingError=0x160ebd8f0 {Error Domain=NSPOSIXErrorDomain Code=1
"Operation not permitted"}}
I'm trying to extract Data from a url of video asset from the Photo's framework which is something like this :
file:///var/mobile/Media/DCIM/104APPLE/IMG_4155.MP4
However I m successful in extracting photos using the same method not the videos..
I m using these lines to extract the video :
let urlNew = URL(fileURLWithPath: item.finalVideoForServer)
let videoData = try Data(contentsOf: urlNew)
Kindly help me or correct me if I'm wrong.
You have to add following lines to your info.plist file(open in source code view) in your project directory
<!-- 🖼 Photo Library -->
<key>NSPhotoLibraryUsageDescription</key>
<string>$(PRODUCT_NAME) photo use</string>
<!-- 📷 Camera -->
<key>NSCameraUsageDescription</key>
<string>$(PRODUCT_NAME) camera use</string>

UIImage imageWithContentsOfFile: not working on real device

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.

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.

How to convert video path to NSData

I have used DKImagePicker for fetching multiple videos from gallery. Able to fetch video but not getting convert to NSData. And also receiving error from server.
Error Domain=NSCocoaErrorDomain Code=257 "The file “IMG_0040.MOV” couldn’t be opened because you don’t have permission to view it." UserInfo={NSFilePath=/var/mobile/Media/DCIM/100APPLE/IMG_0040.MOV, NSUnderlyingError=0x172e5f6b0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}
May be not converted to NSData properly or may be some other issue.
what i tried so far is:
let videoURL = User.sharedInstance.arrRoomGalleryVideos.objectAtIndex(index) as? NSURL
var movieData: NSData?
do {
let video = try NSData(contentsOfURL: videoURL!, options: .DataReadingMappedIfSafe)
print("video", video)
multipartFormData.appendBodyPart(data: video, name: "video_path[]", fileName: strVidName, mimeType: "mp4")
} catch {
print(error)
return
}
Please guide. Thanks in advance.
You should copy file into Documents or any other place IMMEDIATELY when you get file path from delegate method. Because originally file was placed into private folder, which is temporary as I understand. So when your 3-rd party tool finishes processing and stores into the file - it becomes inaccessible at some point.
So after you copy it using copyItemAtPath:toPath: or something like that - you may get NSData by reading it from new path.
From DKImagePicker git I found method: writeAVToFile(path:presetName:completeBlock:) which may help. Look here.

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