Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Directory in Swift 3.0

Tags:

ios

swift

swift3

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.

like image 549
Neeld Avatar asked Dec 15 '16 11:12

Neeld


People also ask

How do I create a directory in Swift?

Swift – Create Directory at Specific Path To create a Directory at specific path in Swift, call createDirectory() function on the file manager object. The following code snippet creates Directory at path “/ab/cd/”. withIntermediateDirectories: true creates intermediate directories if not present.

How do I create a folder in Xcode?

Select an item and choose File > New > Group, or Control-click the item and select New Group from the contextual menu. Create a new group without a folder. Select an item and choose File > New > Group without Folder, or Control-click the item and select New Group without Folder from the contextual menu.

How do I open the file manager in IOS Swift?

Do a print(path. absoluteString) and then $ open path in Terminal, to open the file or folder at path. Keep in mind that the directory (on your Mac) where a Simulator's files are stored can change between running your app.


1 Answers

Please use this code:

Swift 5.0, Swift 4.0 And Swift 3.0

let DocumentDirectory = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]) let DirPath = DocumentDirectory.appendingPathComponent("FOLDER_NAME") do {     try FileManager.default.createDirectory(atPath: DirPath!.path, withIntermediateDirectories: true, attributes: nil) } catch let error as NSError {     print("Unable to create directory \(error.debugDescription)") } print("Dir Path = \(DirPath!)") 
like image 121
Pragnesh Vitthani Avatar answered Sep 27 '22 15:09

Pragnesh Vitthani