How to find a correct path in Swift - ios

I got this code from the documentation, I can't find the path to my file, I need to copy the "contacts.db" file from Supporting Files Folder to the app in the device not in the simulator for offline use.
func copyItemAtPath(_ srcPath: String,
toPath dstPath: String,
error error: NSErrorPointer) -> Bool
srcPath = The path to the file or directory you want to move. This parameter must not be nil.
dstPath = The path at which to place the copy of srcPath. This path must include the name of the file or directory in its new location. This parameter must not be nil.
error = On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information.
Any help is highly appreciated. :)

You can just drag and drop "contacts.db" into Project Navigator and after that you can find a path of that file this way:
let sourcePath = NSBundle.mainBundle().pathForResource("contacts", ofType: "db")
after that you can copy that file into document folder of your app and for that you need that document folder path:
let doumentDirectoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String
let destinationPath = doumentDirectoryPath.stringByAppendingPathComponent("contacts1.db")
now you have sourcePath and destinationPath so you can copy that file into document folder:
NSFileManager().copyItemAtPath(sourcePath!, toPath: destinationPath, error: &error)
and if you want to check for error you can do it this way:
var error : NSError?
NSFileManager().copyItemAtPath(sourcePath!, toPath: destinationPath, error: &error)
if let error = error {
println(error.description)
}
If you are getting your sourcePath nil then goto Targets->YouApp->Build Phases->copy Bundle Resources and add your file there.
Hope this will help.

Related

Error when attempting to move item using FileManager

I have a few items that are saved to the documents directory. I currently need those to be moved programmatically to another directory. I created the new directory successfully, but it doesn't seem to be looking at that when using FileManager.default.moveItem.
Code used to created directory.
let path = getDocumentsDirectory().appendingPathComponent("Media").path
do{
try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: false, attributes: nil)
print("\nDIRECTORY 'Media' CREATED")
}catch {
print("\nDIRECTORY 'Media' WAS NOT ABLE TO BE CREATED")
print("ERROR - \(error)")
}
I use this code to check my URL.
let mediaURL = getDocumentsDirectory().appendingPathComponent("Media")
print("\nMEDIA URL: \(mediaURL)")
Which outputs this.
MEDIA URL:file:///Users/joseph/Library/Developer/CoreSimulator/Devices/552B72BF-8929-40EE-A75B-4574D3D2918A/data/Containers/Data/Application/E168B872-6A1D-4D78-B460-D45194088E5B/Documents/Media/
Here is the code I'm using to move the items.
do{
try FileManager.default.moveItem(at: url, to: mediaURL)
print("\nFILE MOVED TO NEW MEDIA PATH SUCCESSFULLY")
}catch {
print("\nCOULDN'T MOVE FILE TO NEW MEDIA PATH")
print("ERROR - \(error)")
}
Here is the error I'm receiving for each item that I try to move.
COULDN'T MOVE FILE TO NEW MEDIA PATH
ERROR - Error Domain=NSCocoaErrorDomain Code=516 "“image_5” couldn’t be moved to “Documents” because an item with the same name already exists." UserInfo= {NSSourceFilePathErrorKey=/Users/joseph/Library/Developer/CoreSimulator/Devices/552B72BF-8929-40EE-A75B-4574D3D2918A/data/Containers/Data/Application/E168B872-6A1D-4D78-B460-D45194088E5B/Documents/image_5, NSUserStringVariant=(
Move
), NSDestinationFilePath=/Users/joseph/Library/Developer/CoreSimulator/Devices/552B72BF-8929-40EE-A75B-4574D3D2918A/data/Containers/Data/Application/E168B872-6A1D-4D78-B460-D45194088E5B/Documents/Media, NSFilePath=/Users/joseph/Library/Developer/CoreSimulator/Devices/552B72BF-8929-40EE-A75B-4574D3D2918A/data/Containers/Data/Application/E168B872-6A1D-4D78-B460-D45194088E5B/Documents/image_5, NSUnderlyingError=0x60000024fff0 {Error Domain=NSPOSIXErrorDomain Code=17 "File exists"}}
The media directory should be empty, as it is newly created, so the error I'm receiving is a bit confusing. It's also saying it's trying to move it to 'Documents', but it should be moving to 'Media'.What is causing this issue, and how can I resolve it? I'm just trying to move the items saved in 'Documents' to the new directory, 'Media'.
You must append the file name to the destination URL. Per the docs:
The new location for the item in srcURL. The URL in this parameter must not be a file reference URL and must include the name of the file or directory in its new location. This parameter must not be nil.
Delete the old file if exist
let url = NSUrl(string: "...")
if NSFileManager.defaultManager().fileExistsAtPath(url.path!) {
try! NSFileManager.defaultManager().removeItemAtURL(url)
}
Update:
Swift 5.1.2
let url = URL(string: mp3FilePath)
if FileManager.default.fileExists(atPath: url!.path) {
try! FileManager.default.removeItem(at: url!)
}
This worked for me - Add the name of file too in destination path
let nameFile = (songPath as NSString).lastPathComponent
let fileDest = destinationDirectoryPath + "/" + nameFile
//Now move the song files
try fileManager.moveItem(atPath: sourceFilePath, toPath: fileDest)

How to correctly reference/retrieve a temp file created in AppData for file upload to a server?

So the app I'm making creates a file called "logfile" and I'm trying to send that file via Alamofire upload to a server. The file path printed in the console log is
/var/mobile/Containers/Data/Application/3BE13D78-3BF0-4880-A79A-27B488ED9EFE/Documents/logfile.txt
and the file path I can use to manually access the log created in the .xcappdata is
/AppData/Documents/logfile.txt
To access it, I'm using
let fileURL = Bundle.main.url(forResource: "", withExtension: "txt")
where inbetween the double quotes for "forResource", I've tried both file paths I listed in the previous paragraph as well as just the file name but I'm getting a nil value for file found for either. The file isn't recognized to be there, presumably because the file path I'm using is wrong as Alamofire is returning nil when trying to locate send the file. Anyone know the direct file path I'm supposed to use to be able to grab my file since the other two don't supposedly work? Thank you!
Use below code to get string data from text file to upload to server:
let fileName = "logfile"
let documentDirURL = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = documentDirURL.appendingPathComponent(fileName).appendingPathExtension("txt")
print("FilePath: \(fileURL.path)")
var readString = "" // Used to store the file contents
do {
// Read the file contents
readString = try String(contentsOf: fileURL)
} catch let error as NSError {
print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
}
print("File Text: \(readString)") // Send 'readString' to server
If you're dynamically creating the file at runtime, it won't be in your app bundle so the Bundle class won't be able to find it. The directories you see are also dynamically-generated and not only platform-specific, but also device-specific, so you can't use the file paths directly. Instead, you'll have to ask for the proper directory at runtime from the FileManager class, like this:
guard let documents = FileManager.default.urls(for: .documentsDirectory, in: .userDomainMask).first else{
// This case will likely never happen, but forcing anything in Swift is bad
return
}
let logURL = URL(string: "logfile.txt", relativeTo: documents)
do{
let fileContents = String(contentsOf: logURL)
// Send your file to your sever here
catch{
// Handle any errors you might've encountered
}
Note that I'm guessing based on the paths you pasted in your answer you put it in your application's documents directory. That's a perfectly fine place to put this type of thing, but if I'm wrong and you put it in a different place, you'll have to modify this code to point to the right place

i have an issue on the file System on the actual device

my problem is when i try to copy images from the photo library to the filesystem i get the error the error is
(Error Domain=NSCocoaErrorDomain Code=257 "The file “IMG_0926.JPG”
couldn’t be opened because you don’t have permission to view it."
UserInfo={NSFilePath=/var/mobile/Media/DCIM/100APPLE/IMG_0926.JPG,
NSUnderlyingError=0x15649630 {Error Domain=NSPOSIXErrorDomain Code=1
"Operation not permitted"}})
my code is :
let fileManager = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let document = fileManager[0]
var i = 0
for asset in arrayOfAssets {
let filePath = document.appendingPathComponent("image\(arrayOfAssets.count + i).png")
i += 1
PHImageManager.default().requestImageData(for: asset, options: nil) { (data, nil, _ , info) in
let url = info?["PHImageFileURLKey"] as! NSURL
do {
try FileManager.default.copyItem(at: url as URL, to: filePath)
}catch {
print(error)
}
// print(filePath)
}
}
please if anyone can help me
thanks all
It sounds like you're trying to open a file located here : NSFilePath=/var/mobile/Media/DCIM/100APPLE/IMG_0926.JPG
By default access to this directory is not permitted, you can only access files located in the document directory, for security reasons.
I don't find where this URL comes from in your code, but according to the NSError you are trying to access an image outside the permitted area of the file system.
Please check the permission option in plist for Photos Library in iOS 11.
Also you can save data in TEMP directory and fetch it when needed and after use
clean data in TEMP directory.

Swift : Dropbox image upload fails due to RegEX pattern match failing

I am using SwiftyDropbox API to upload images to dropbox. I have image in project directory and trying to upload it like this :
// Verify user is logged into Dropbox
if let client = Dropbox.authorizedClient {
let imagePath : NSString = NSBundle.mainBundle().pathForResource("abc", ofType: "png")!
print("Path :--> \n", imagePath)
let url : NSURL = NSURL(string: imagePath as String)!
client.files.upload(path: "", body: url).response{response, error in
if let metadata = response {
print("*** Upload file ****")
print("Uploaded file name: \(metadata.name)")
self.delegate?.imageSavedSuccessfully()
}
else{
print(error!)
}
}
And the error I get is (including screenshot too.):
precondition failed: " must match pattern "\A(?:/.*)\z":
Any hint or guide what I am doing wrong? Thank you in advance.
For your file upload, you're specifying the path "", but that represents the root folder, not a file path.
Instead, the path should be the full path where you want to upload the file, including the file name. For example, to upload the file as "abc.png" in the root of the Dropbox account, you'd specify the path as "/abc.png".

Swift: copying files gives Cocoa Error 262

I'm trying to move my files up a level in some random directory in the default Documents directory. But when copying, Swift gave me the error Cocoa Error 262: NSFileReadUnsupportedSchemeError. Why did I get this error? I ran a quick search and pretty much everyone who'd encountered this problem was trying to copy files out of the camera roll, but I'm not. Any thoughts? Thanks in advance.
Code here:
private func copyFilesInDirectory(fromDir: String, toDirectory toDir: String, withCompletionHandler handler: ()->()){
println("from: \(fromDir)\nto: \(toDir)")
var error: NSError?
var contents = fileManager.contentsOfDirectoryAtPath(fromDir, error: &error)
if let dirContents = contents{
let enumerator = (dirContents as NSArray).objectEnumerator()
while let file = enumerator.nextObject() as? String{
let filePath = fromDir.stringByAppendingString("/\(file)")
println("copying \(filePath)")
if(fileManager.copyItemAtURL(NSURL(fileURLWithPath: filePath)!, toURL: NSURL(string: toDir)!, error: &error)){
println("COPIED")
}
else{
println("COPY ERROR: \(error!.localizedDescription)")
}
}
handler()
}
}
and here's the log if anyone's interested:
from: /Users/dolce/Library/Developer/CoreSimulator/Devices/05566649-BABB-44BE-BE6F-AFF7B41E3065/data/Containers/Data/Application/F5A83C94-C177-4826-BDD5-3A50E7508239/Documents/Hello/tmp
to: /Users/dolce/Library/Developer/CoreSimulator/Devices/05566649-BABB-44BE-BE6F-AFF7B41E3065/data/Containers/Data/Application/F5A83C94-C177-4826-BDD5-3A50E7508239/Documents/Hello
copying /Users/dolce/Library/Developer/CoreSimulator/Devices/05566649-BABB-44BE-BE6F-AFF7B41E3065/data/Containers/Data/Application/F5A83C94-C177-4826-BDD5-3A50E7508239/Documents/Hello/tmp/test.png
COPY ERROR: The operation couldn’t be completed. (Cocoa error 262.)
The toURL parameter of copyItemAtURL() must not be the destination
directory, but the URL of the destination file. This can be
created with
let destPath = toDir.stringByAppendingPathComponent(file)
You should also replace
let filePath = fromDir.stringByAppendingString("/\(file)")
with
let filePath = fromDir.stringByAppendingPathComponent(file)
There is also a copyItemAtPath() method which saves you from
converting the paths to URLs.
On an iOS device, the simple answer is you can't do that. On the simulator things are little different. What you're probably dealing with is file permissions on the directory you're trying to write to.
As a general rule on iOS, you can write to the designated directories like the documents/caches and nothing else.

Resources