Advertisement
Guest User

files

a guest
May 24th, 2018
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.26 KB | None | 0 0
  1. //
  2. //  ViewController.swift
  3. //  MyFiles
  4. //
  5. //  Created by Hackeru_Student on 5/24/18.
  6. //  Copyright © 2018 Hackeru_Student. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10.  
  11. class ViewController: UIViewController {
  12.    
  13.     //outlets
  14.     @IBOutlet weak var txt: UITextField!
  15.     @IBOutlet weak var data: UITextView!
  16.     //variables
  17.     //for creating a string for file name location
  18.     var documentPath, fileName, fullPath: String!
  19.     //for getting the ios defualt file manager
  20.     var fileManager = FileManager.default
  21.    
  22.     override func viewDidLoad() {
  23.         super.viewDidLoad()
  24.         fileSettings()
  25.     }
  26.  
  27.     //actions
  28.     @IBAction func btnWrite(_ sender: Any) {
  29.         if txt.text!.isEmpty {return}
  30.         //writeToFile(txt: readFromFile()+txt.text!+"\r")
  31.         writeToFile(readFromFile()+txt.text!+"\r")
  32.         data.text! = readFromFile()
  33.         txt.text=""
  34.     }
  35.    
  36.     @IBAction func btnRead(_ sender: Any) {
  37.         data.text! = readFromFile()
  38.     }
  39.    
  40.     @IBAction func btnDelete(_ sender: Any) {
  41.         do
  42.         {
  43.             try fileManager.removeItem(atPath: fullPath)
  44.             data.text! = ""
  45.         }
  46.         catch
  47.         {
  48.             print ("can not delete file")
  49.         }
  50.     }
  51.    
  52.     //methods
  53.     fileprivate func fileSettings()
  54.     {
  55.         fileName = "husam.txt"
  56.         documentPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]
  57.         fullPath=documentPath+"/"+fileName
  58.         print (fullPath!)
  59.         data.text!=""
  60.     }
  61.    
  62.     fileprivate func writeToFile (_ txt:String)
  63.     {
  64.         do
  65.         {
  66.             try txt.write(toFile: fullPath, atomically: true, encoding: String.Encoding.utf8)
  67.         }
  68.         catch
  69.         {
  70.             print ("can not write to file!!!!")
  71.         }
  72.     }
  73.    
  74.     fileprivate func readFromFile()->String
  75.     {
  76.         var temp=""
  77.         if fileManager.fileExists(atPath: fullPath)
  78.         {
  79.             do{
  80.                 try temp = String(contentsOfFile: fullPath)
  81.             }
  82.             catch{
  83.                 print ("can not open file for read")
  84.             }
  85.         }
  86.         return temp
  87.     }
  88.  
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement