i am creating a directory so that i can save temp videos onto it as TempVideos is a folder now my video clips will be inside the folder...
func createTempDirectoryToStoreVideos(){
var error: NSError?
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let documentsDirectory: AnyObject = paths[0]
tempVideoPath = documentsDirectory.stringByAppendingPathComponent("TempVideos")
if (!NSFileManager.defaultManager().fileExistsAtPath(tempVideoPath!)) {
NSFileManager.defaultManager() .createDirectoryAtPath(tempVideoPath!, withIntermediateDirectories: false, attributes: nil, error: &error)
}
}
Now in these directory i want to store the videos as
func saveCompressVideoToTempDirectory(var compressedVideoUrl:NSURL?){
let data = NSData(contentsOfURL: compressedVideoUrl!)
var error:NSError?
var success = data?.writeToFile(tempVideoPath!, options: NSDataWritingOptions.AtomicWrite, error: &error)
println(error)
if let temp = success{
if temp {
println("success")
}else{
println("not valid ")
}
}
}
Howver i get error as
Optional(Error Domain=NSCocoaErrorDomain Code=512 "The operation
couldn’t be completed. (Cocoa error 512.)" UserInfo=0x17407f6c0
{NSFilePath=/var/mobile/Containers/Data/Application/F1140A9F-8D16-444B-8679-9ED1AD3F5E6A/Documents/TempVideos,
NSUnderlyingError=0x17424a320 "The operation couldn’t be completed. Is
a directory"})
Could you try createFileAtPath for that?
func createFileAtPath(_ path: String,
contents data: NSData?,
attributes attr: [String : AnyObject]?) -> Bool
The same thing concerns writeToFile:
func writeToFile(_ path: String,
options writeOptionsMask: NSDataWritingOptions) throws
where, look out, path is
The location to which to write the receiver's bytes. If path contains
a tilde (~) character, you must expand it with
stringByExpandingTildeInPath before invoking this method.
You should write this:
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
var dirpath: String = paths[0] as String
let filepath = dirpath.stringByAppendingPathComponent("myOwnData.mov")
Related
I'm making a game on iPad (v10.2.1) with Xcode(version 8.2.1) and while I'm trying to save some data in documents folder in the sandbox, I found that all ways I tried failed: createDirectory and createFile(using file manager), and writeToUrl(using NSData). I ran the program on 2 iPads and 1 iPhone and no success.
I was able to read from a plist I created, and convert it to a dictionary, using the function convertDataFrom().
I'm new to data persistence or file manipulation and my game stuck here. would appreciate any help!
func loadData()->NSDictionary{
let fm = FileManager()
let sourceUrl = Bundle.main.url(forResource: "Data", withExtension: "plist")!
var appSupportDir = fm.urls(for: .documentDirectory, in: .userDomainMask).first! as? NSURL
appSupportDir = appSupportDir!.appendingPathComponent("UserData", isDirectory: true) as NSURL?
let urlForSave = (appSupportDir!.appendingPathComponent("Data.plist"))!
//load data, or if file doesn't exist yet, create one
var isDirectory: ObjCBool = false
if fm.fileExists(atPath: urlForSave.absoluteString, isDirectory: &isDirectory) {
let data = convertDataFrom(url: urlForSave)
print("data file exists")
print(isDirectory)
return data as NSDictionary
} else {
do { try fm.createDirectory(atPath: appSupportDir!.absoluteString!, withIntermediateDirectories: true, attributes: nil) }catch let Error {
print("create directory failed")
print(Error)
}
let originalData = NSData.init(contentsOf: sourceUrl)
print("\(urlForSave)")
do { try originalData?.write(toFile: urlForSave.absoluteString, options: .atomic) } catch let Error {
print(Error)
}
if (!fm.createFile(atPath: urlForSave.absoluteString, contents: originalData as Data?, attributes: nil)) {
fatalError("file creation failed")
}
let data = convertDataFrom(url: urlForSave)
print("\(data)")
print(isDirectory)
return data as NSDictionary
}
}
func convertDataFrom(url: URL)->Dictionary<String, Any> {
let dictionary = NSDictionary.init(contentsOf: url) as! Dictionary<String, Any>
return dictionary
}
Error messages for "createDirectory": Error Domain=NSCocoaErrorDomain
Code=513 "You don’t have permission to save the file “UserData” in the
folder “Documents”."
UserInfo={NSFilePath=file:///var/mobile/Containers/Data/Application/F7F41E0D-D3F6-489B-A59E-B7AC401EC402/Documents/UserData/,
NSUnderlyingError=0x174053f50 {Error Domain=NSPOSIXErrorDomain Code=1
"Operation not permitted"}}
file:///var/mobile/Containers/Data/Application/F7F41E0D-D3F6-489B-A59E-B7AC401EC402/Documents/UserData/Data.plist
and for "createFile" (fatalError if createFile fails) Error
Domain=NSCocoaErrorDomain Code=4 "The file “Data.plist” doesn’t
exist."
UserInfo={NSFilePath=file:///var/mobile/Containers/Data/Application/F7F41E0D-D3F6-489B-A59E-B7AC401EC402/Documents/UserData/Data.plist,
NSUnderlyingError=0x174055bd0 {Error Domain=NSPOSIXErrorDomain Code=2
"No such file or directory"}} fatal error: file creation failed: file
/Users/chanwu/Desktop/Math_DownStairs/Math_DownStairs/
Your code checks to see if urlForSave (the final file) exists, and if it doesn't, you then try to create the UserData directory.
If the final file doesn't exist, but the UserData directory does, I would expect the exact outcome you describe.
You should probably change your test to see if the UserData directory exists instead of testing for the final file. That way if the directory doesn't exist you'll create it, and then call write(toFile:), which will create the file if it doesn't exist.
After transferring a file from iPhone to Apple Watch I get the Error
Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"
What do I do wrong? These are the code snippets:
iPhone ViewController
func makeAction () {
let url = NSURL.fileURL(withPath: fileArray[0].object(at: 2) as! String)
var applicationDict = Dictionary<String, Array<AnyObject>>()
applicationDict["fileArray"] = fileArray
WCSession.default().transferFile(url, metadata: applicationDict)
}
Watch InterfaceController
func session(_ session: WCSession, didReceive file: WCSessionFile) {
DispatchQueue.main.async(execute: { () -> Void in
print("RECEIVED")
var applicationDict = Dictionary<String, Array<AnyObject>>()
applicationDict = file.metadata as! Dictionary<String, Array<AnyObject>>
self.fileArray = applicationDict["fileArray"]!
self.fileList = self.fileArray
let dirPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let tempDocsDir = dirPaths[0] as String
let docsDir = tempDocsDir.appending("/")
let filemgr = FileManager.default
do {
let fileName = self.fileArray[0].object(at: 1) as! String
try filemgr.moveItem(atPath: file.fileURL.path, toPath: docsDir + fileName)
} catch let error as NSError {
print("Error moving file: \(error.description)")
}
self.loadTableData()
})
}
Full Error Message
Error moving file: Error Domain=NSCocoaErrorDomain Code=4
"“5d1392cd-acac-4b99-abf5-50062e12dc14_95de54df-69b1-43df-bb90-cfac6fed3677.mp3” couldn’t be moved to “Documents” because either the former doesn't
exist, or the folder containing the latter doesn't exist."
UserInfo={NSSourceFilePathErrorKey=/Users/pknapp/Library/Developer/CoreSimulator/Devices/950FC0DA-C245-4326-8777-80CE765AF655/data/Containers/Data/PluginKitPlugin/73C0D94F-483C-4426-B052-001E8837D83A/Documents/Inbox/com.apple.watchconnectivity/FCE7E6CB-2452-4E0A-9AFF-F5B3A51A0DE8/Files/0B96CCB0-A2E1-418B-9859-97C22238A5F5/5d1392cd-acac-4b99-abf5-50062e12dc14_95de54df-69b1-43df-bb90-cfac6fed3677.mp3, NSUserStringVariant=(
Move ), NSFilePath=/Users/pknapp/Library/Developer/CoreSimulator/Devices/950FC0DA-C245-4326-8777-80CE765AF655/data/Containers/Data/PluginKitPlugin/73C0D94F-483C-4426-B052-001E8837D83A/Documents/Inbox/com.apple.watchconnectivity/FCE7E6CB-2452-4E0A-9AFF-F5B3A51A0DE8/Files/0B96CCB0-A2E1-418B-9859-97C22238A5F5/5d1392cd-acac-4b99-abf5-50062e12dc14_95de54df-69b1-43df-bb90-cfac6fed3677.mp3, NSDestinationFilePath=/Users/pknapp/Library/Developer/CoreSimulator/Devices/950FC0DA-C245-4326-8777-80CE765AF655/data/Containers/Data/PluginKitPlugin/73C0D94F-483C-4426-B052-001E8837D83A/Documents/5d1392cd-acac-4b99-abf5-50062e12dc14_95de54df-69b1-43df-bb90-cfac6fed3677.mp3, NSUnderlyingError=0x7b776110 {Error Domain=NSPOSIXErrorDomain Code=2
"No such file or directory"}}
The documentation for didReceiveFile notes:
File: The object containing the URL of the file and any additional information. If you want to keep the file referenced by this parameter, you must move it synchronously to a new location during your implementation of this method. If you do not move the file, the system deletes it after this method returns.
So make sure to not async in this method before moving the file to a location your app has access to.
Alright, got it. putting this in an async dispatch was wrong. Without ist -> work perfectly. Please go ahead, nothing to see here :)
I am getting an error when writing an image file to a directory in Xcode. The function data.writeToFile is returning an error. Here is what I am trying to do:
Get The File Path:
func getPath(fileName: String) -> String {
let documentURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let folder = "sampleDirectory"
return documentURL.URLByAppendingPathComponent(folder).URLByAppendingPathComponent(fileName).path!
}
Save the Image
func saveImage(image: UIImage, path: String) -> Bool {
let pngImageData = UIImagePNGRepresentation(image)
do {
let success = try pngImageData?.writeToFile(path, options: NSDataWritingOptions.init(rawValue: 0))
} catch {
print(error)
}
return false
}
However, there is an error saying:
NSPOSIXErrorDomain - code : 2
Does anyone know what the problem could be?
EDIT
Where I call the code:
let fileName = "first_image"
let imagePath = self.getPath(fileName)
let result = self.saveImage(processedImage, path: imagePath)
processedImage is of type UIImage!
Try creating the directory "sampleDirectory" if it does not exists or don't use a subdirectory.
You can check if the directory exists with:
if !NSFileManager.defaultManager().fileExistsAtPath(path) {
// create missing directories
try! NSFileManager.defaultManager().createDirectoryAtPath(foo, withIntermediateDirectories: true, attributes: nil)
}
You also might want to use the option NSDataWritingOptions.DataWritingAtomic which first write to an auxiliary file first and then exchange the files if there were no errors
I am using a sequence of three functions to play a video using AVPlayerViewController on iOS :
first I add the video files to my project by copying them to my project root folder and then drag and drop them in xcode project root
First Function that copies the file to the application's document folder :
a. Get the document path
class func getPath(fileName: String) -> String{
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let fileURL = documentsURL.URLByAppendingPathComponent(fileName)
return fileURL.path!
}
b. COPY THE FILE
class func copyFile(fileName: NSString) {
let dbPath: String = getPath(fileName as String)
let fileManager = NSFileManager.defaultManager()
if !fileManager.fileExistsAtPath(dbPath) {
let documentsURL = NSBundle.mainBundle().resourceURL
print(documentsURL)
let fromPath = documentsURL!.URLByAppendingPathComponent(fileName as String)
var error : NSError?
do {
try fileManager.copyItemAtPath(fromPath.path!, toPath: dbPath)
} catch let error1 as NSError {
print(error1.localizedDescription)
}
}
}
In my app delegate application(...) function I call Util.copyFile("EVGS_VID1.MOV")
in a view controller I have a function playVideo(fileName:String) :
func playVideo(fileName:String){
let videoPath:String = Util.getPath(fileName)
var fileSize : UInt64 = 0
//Check if file exists
do {
let attr : NSDictionary? = try NSFileManager.defaultManager().attributesOfItemAtPath(videoPath)
if let _attr = attr {
fileSize = _attr.fileSize();
}
} catch {
print("Error: \(error)")
}
let playerViewController:AVPlayerViewController = AVPlayerViewController()
var url:NSURL = NSURL(fileURLWithPath: videoPath,isDirectory: false)
let player = AVPlayer(URL: url)
playerViewController.player = player
self.presentViewController(playerViewController, animated: true) {
playerViewController.player!.play()
}
}
but when I call the playVideo in my view controller it shows the player with no video and I got an exception :
Error: Error Domain=NSCocoaErrorDomain Code=260 "The file “EVGS_VID1.mov” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/var/mobile/Containers/Data/Application/61169756-1DCE-49B1-99F4-27854DDF4929/Documents/EVGS_VID1.mov, NSUnderlyingError=0x1572bbbf0 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
I am using the same functions copyFile and getPath to copy SQLite database and it's working
I am trying to copy a file in the documents directory to a directory within the documents directory but i am getting an error couldn’t be copied to “Documents” because an item with the same name already exists.
Any help would be appreciated.
Here is my code:
let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])
let logsPath = documentsPath.URLByAppendingPathComponent("Logs")
let fileURL = documentsPath.URLByAppendingPathComponent("Database.db")
do {
try NSFileManager.defaultManager().copyItemAtURL(fileURL, toURL: logsPath)
} catch let error1 as NSError{
RZLog.Error ("Error: \(error1.localizedDescription)")
}
There's more than one way to do it.
The simplest one would be to remove the destination file before copying it:
try! NSFileManager.removeItemAtURL(dstURL)
You may want to handle all the file management errors in a single place by implementing NSFileManagerDelegate:
Set NSFileManager().delegate to your class (where you're copying the file)
Intercept the error implementing one of the delegate methods. Depending on the error you can do different stuff to recover. Return true to continue or false to abort.
Example:
class AnyClass : NSFileManagerDelegate {
let fileManager = NSFileManager()
func fileManager(fileManager: NSFileManager, shouldProceedAfterError error: NSError, copyingItemAtURL srcURL: NSURL, toURL dstURL: NSURL) -> Bool {
if error.code == NSFileWriteFileExistsError {
try! fileManager.removeItemAtURL(dstURL)
copyFrom(srcURL, to: dstURL)
return true
} else {
return false
}
}
func copyFrom(a: NSURL, to b: NSURL) {
try! fileManager.copyItemAtURL(a, toURL: b)
}
func entryPoint() {
fileManager.delegate = self
copyFrom(sourceURL, to: destinationURL)
}
}