I am a new student in 9th grade learning swift, creating a school project .
I am trying to create a directory where I want to save a scanned file into pdf format.
While creating directory I am getting error below.
Error 1:
Cannot use instance member 'filemgr' within property initializer; property initializers run before 'self' is available.
Error 2:
Expected declaration
Code:
let filemgr = FileManager.default
let dirPaths = filemgr.urls(for: .documentDirectory, in: .userDomainMask)
let docsURL = dirPaths[0]
let newDir = docsURL.appendingPathComponent("data").path
do{
try filemgr.createDirectory(atPath: newDir,withIntermediateDirectories: true, attributes: nil)
} catch {
print("Error: \(error.localizedDescription)")
}
Please assist me in resolving this issue.
Thanks.
For Swift 4.0, I created the following extension off of
URL
that allows for the creation of a folder off of the documents directory within the application.If the desired folder does not exist, it will create it. Then, assuming the folder exists, it returns the
URL
back to the user. Otherwise, if it fails, thennil
is returned.For example, to create the folder "MyStuff", you would call it like this:
This would return:
You can also create nested folders with the following:
Which gives you:
For Swift 4.0 Please use this
You are getting this because you are assigning value to
newDir
instance at wrong place.I wrote your code in
viewDidLoad
and it works perfectly.Pls, use this code:
Swift 4.0 And Swift 3.0