Advertisement
Guest User

read write delete file

a guest
Apr 1st, 2020
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.24 KB | None | 0 0
  1. //files and ios sand box.....
  2. import UIKit //you must import UIKit for getting all the extra commands
  3.  
  4. class FileWritter{
  5.     //variebles
  6.     //for createing string filename location
  7.     var documentPath, fileName, fullPath:String!
  8.     //for getting the ios file manager
  9.     var fileManager = FileManager.default
  10.    
  11.     init() {
  12.         fileSettings()
  13.     }
  14.    
  15.     func fileSettings(){
  16.         //name of file
  17.         self.fileName = "zeev.txt"
  18.         //for getting document path, we need to use our file manager....
  19.         self.documentPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]
  20.        
  21.         self.fullPath = "\(documentPath!)/\(fileName!)"
  22.     }
  23.    
  24.     func test(){
  25.         print (self.fullPath!)
  26.     }
  27.    
  28.     func writeToFile(_ txt:String){
  29.         var myData = readFromFile()
  30.         myData += txt
  31.         do{
  32.             try myData.write(toFile: self.fullPath, atomically: true, encoding: String.Encoding.utf8)
  33.             print ("wrote to file")
  34.         } catch {
  35.             print ("Error writting to file...")
  36.         }
  37.     }
  38.    
  39.     func readFromFile()->String{
  40.         var temp = ""
  41.         if fileManager.fileExists(atPath: fullPath){
  42.             //read from file
  43.             do{
  44.                 try temp = String(contentsOfFile: self.fullPath)
  45.             } catch {
  46.                
  47.                 //in string we can add ?? "with defualt value"
  48.                 print ("we can not read from file \(self.fileName ?? "filename currptted")")
  49.             }
  50.         } else {
  51.             print ("there is no file in the system")
  52.         }
  53.         return temp
  54.     }
  55.    
  56.     func deleteFile(){
  57.         do{
  58.             print ("file was deleted")
  59.             try fileManager.removeItem(atPath: fullPath)
  60.         } catch {
  61.             print ("can not delete the file...")
  62.         }
  63.     }
  64. }
  65.  
  66. var test = FileWritter()
  67. test.deleteFile()
  68. print (test.readFromFile())
  69. test.writeToFile("let's do what we did last night \n")
  70. print (test.readFromFile())
  71. test.writeToFile("we will rule the world !!")
  72. print (test.readFromFile())
  73. test.deleteFile()
  74. test.writeToFile("zeev")
  75. print (test.readFromFile())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement