This question already has answers here:
Iterate through files in a folder and its subfolders using Swift's FileManager
(14 answers)
Closed 8 years ago.
Just trying to make a for..in loop for files in the local app folder
let filemanager:NSFileManager = NSFileManager()
let files = filemanager.enumeratorAtPath(NSHomeDirectory())
for filename in files!
{
println(filename)
}
But it says Type 'NSDirectoryEnumerator' doesn't conform to protocol SequenceType.
I think this may be possible by implementing an extension to NSFileManager that implements the SequenceType protocol. But you could easily convert your code to using a while loop:
let filemanager:FileManager = FileManager()
let files = filemanager.enumerator(atPath: NSHomeDirectory())
while let file = files?.nextObject() {
print(file)
}
Related
This question already has answers here:
Swift - encode URL
(19 answers)
Closed 5 years ago.
I tried to call a custom url using this code below:
let myurl = "https://myserver.com/call?a|b|c"
let converted = URL(string: myurl)
print(converted)
But what I'm getting as result in converted is just "nil".
I'm pretty sure this is because of the wrong characters set in relation to the URL() class.
After some research all I got so far is this outdated Swift code:
var myurl = "https://myserver.com/call?a|b|c"
var newurl = myurl.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
print(newurl)
But it doesn't seems working this way.
How can I achieve to avoid the "nil" result using (in my case) Swift 4?
Found the solution on my own:
let myurl = "https://myserver.com/call?a|b|c"
let converted = URL(string: myurl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
print(converted!)
The new function is called addingPercentEncoding & I have to call it with the urlQueryAllowed property.
The urlQueryAllowed charset adds some characters like this to the url encoding: "!*'();:#&=+$,/?%#[]|"
VoliĆ !
This question already has answers here:
Save An Image To Application Documents Folder From UIView On IOS
(6 answers)
Closed 5 years ago.
I want to in my app, be able to allow users to save large images(jpg) as well as data for each image(txt) and load the images/data. I'm having trouble figuring out where to save these images and text files. Userdefault wouldnt work because of the size of the image files and I don't want to save in the documents directory because then the user can access and potentially corrupt the data.
Where is a good place to save large data files for my app so I can load them later?
You can save and retrieve your files in application directory folder. Also you can use iCloud to save your files.
Use below code if you want to save and retrieve files from Directory folder .
Xcode 8.3.2 Swift 3.x. Using NSKeyedArchiver and NSKeyedUnarchiver
Reading file from documents
let documentsDirectoryPathString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let documentsDirectoryPath = NSURL(string: documentsDirectoryPathString)!
let jsonFilePath = documentsDirectoryPath.appendingPathComponent("Filename.json")
let fileManager = FileManager.default
var isDirectory: ObjCBool = false
if fileManager.fileExists(atPath: (jsonFilePath?.absoluteString)!, isDirectory: &isDirectory) {
let finalDataDict = NSKeyedUnarchiver.unarchiveObject(withFile: (jsonFilePath?.absoluteString)!) as! [String: Any]
}
else{
print("File does not exists")
}
Write file to documents
NSKeyedArchiver.archiveRootObject(finalDataDict, toFile:(jsonFilePath?.absoluteString)!)
If for some reason you don't want to use the documents directory, or you want those data in a separate folder, or you don't want to permanently save them, you can also create your own temporary directory
saving data as file in a new directory (swift 3):
func saveToMyDirectory(data: Data, filename: String) {
var tempDirectoryURL = NSURL.fileURL(withPath: NSTemporaryDirectory(), isDirectory: true)
tempDirectoryURL = tempDirectoryURL.appendingPathComponent(filename)
do {
try data?.write(to: tempDirectoryURL)
} catch {}
}
Alternative approach: use Apple's UIDocumentInteractionController or UIActivityViewController and let the user choose how to save his/her documents:
https://developer.apple.com/documentation/uikit/uidocumentinteractioncontroller
https://developer.apple.com/documentation/uikit/uiactivityviewcontroller
This question already has an answer here:
Xcode 8.2.1 / Swift 3 - Load TableView from Plist Array of Dictionaries
(1 answer)
Closed 5 years ago.
early this month i started learning swift as i found it fun and easier than obj-c
i came up with an idea trying to show english words and meaning on my language,
for that case i have a plist ready on my hand and a UITableViewController
with 2 Labels
here is my plist
so on my UITableViewController, i tried to get hands on the plist file with this code
let path = NSBundle.mainBundle().pathForResource("TableData", ofType: "plist")
let array = Array(contentsOfFile: path!)
and i got stuck on the rest
thanks
If you are just staring to learn Swift please start with Swift 3. Your Swift 2 code is outdated.
The recommended way to load a property list file is PropertyListSerialization
let url = Bundle.main.url(forResource: "TableData", withExtension: "plist")!
do {
let data = try Data(contentsOf: url)
let dataArray = try PropertyListSerialization.propertyList(from: data, format: nil) as! [[String:String]]
print(dataArray)
} catch {
print("This error must not happen", error)
}
This question already has an answer here:
Loading from mainBundle
(1 answer)
Closed 5 years ago.
public func dataFromFile(_ filename: String) -> Data? {
#objc class TestClass: NSObject { }
let bundle = Bundle(for: TestClass.self)
if let path = bundle.path(forResource: filename, ofType: "json") {
return (try? Data(contentsOf: URL(fileURLWithPath: path)))
}
return nil
}
I found this code in a tutorial and am confused on what these two lines do:
#objc class TestClass: NSObject { }
let bundle = Bundle(for: TestClass.self)
I know we have the main bundle for the app but why is it creating a bundle for an objective c class called TestClass?
I know we have the main bundle for the app but why is it creating a bundle for an objective c class called TestClass?
The second bundle is usually a framework. Since the code is from a tutorial, likely the author wants to explain, what bundles are and how you access them.
Having a class you do not need to do that, because the runtime environment searches for the right bundle of a class. But if you want to load other resources (videos, images, sounds, and so on), you have to do it you own. To get the right bundle, you can ask a class residing there for its bundle.
I need to be able to reference a file which is stored in my Xcode project in the following way:
I want to be able to use files which I have stored inside of the "data" folder.
How do I reference it to be able to read its contents? What is it's directory path?
I just figured it out. The apple swift documentation and other developer references are really unclear about it.
The way you would reference the "data" folder so as to scan the entire contents is by writing the following:
let path = NSBundle.mainBundle().resourcePath?.stringByAppendingPathComponent("data")
var error: NSError?
let filesInDirectory: [String]! = fileManager.contentsOfDirectoryAtPath(path!, error: &error) as? [String]
This will return the contents of the files in the "data" folder as an array of filenames.
Hope this helps :)
Relative to swift 3
let bundleURL = Bundle.main.bundleURL
let dataFolderURL = bundleURL.appendingPathComponent("data")
let fileURL = dataFolderURL.appendingPathComponent("file.txt")
print(fileURL.path)
print(FileManager.default.fileExists(atPath: fileURL.path))
let bundleURL = NSBundle.mainBundle().bundleURL
let dataFolderURL = bundleURL.URLByAppendingPathComponent("data")
let fileURL = dataFolderURL.URLByAppendingPathComponent("fileName.txt")