Rewrite or delete existing .png file in IOS swift apllication - ios

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.

Related

iOS App Group Directory write not permitted

When my app is launching I am creating the directory to store some files that later can be shared with extension.
To get the directory I am calling:
let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "com.poster")
Afterwards I am trying to create a custom caches directory.
let posterCachesURL = containerURL.appendingPathComponent("PosterCaches")
do {
try FileManager.default.createDirectory(at: posterCachesURL, withIntermediateDirectories: true)
} catch {
// ... logging error
}
This works just fine, however in production environment some users get this error:
Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file "PosterCaches" in the folder ***folderID***."
UserInfo={NSFilePath=.../PosterCaches,
NSUnderlyingError=0x2401a00c0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}
Have anyone faced this issue?
Thank you in advance!

File not exists while copy from document folder to nsbundle app folder swift

I am trying to save xlsx file from document folder to app folder. Here is code but it showing error:
Error Domain=NSCocoaErrorDomain Code=260 "The file “file1.xlsx” couldn’t be opened because there is no such file." UserInfo={NSFilePath=file:///private/var/mobile/Containers/Data/Application/8AC91C23-3662-44FF-90EF-20F6A34AF61F/Documents/file1.xlsx, NSUnderlyingError=0x16169a60 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
let directoryContents = try NSFileManager.defaultManager().contentsOfDirectoryAtURL( documentsUrl, includingPropertiesForKeys: nil, options: [])
let xlsxFiles = directoryContents.filter{ $0.pathExtension == "xlsx" }
let xlsxFileNames = mp3Files.flatMap({$0.URLByDeletingPathExtension?.lastPathComponent})
var fileManager = NSFileManager.defaultManager()
do {
try fileManager.copyItemAtPath(xlsxFiles[0].absoluteString, toPath: NSBundle.mainBundle().resourcePath! + xlsxFileNames[0] + ".xlsx")
}
catch let error
{
print(error)
}
You have two problems. The first one is causing the error you posted in your question.
Both parameters to copyItemAtPath need to be full file paths. Your first argument is just a file name. You need to append the file name to a full path to its location (similar to what you do for the second argument).
The app's bundle is read-only. You can't copy a file to your app's bundle. So even once you fix the first problem, you will have a new problem. If the file is already inside your app's Documents folder, why do you try to copy it to the bundle?

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.

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

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?

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!

Resources