Read and write a String from text file

前端 未结 21 1444
别跟我提以往
别跟我提以往 2020-11-22 00:02

I need to read and write data to/from a text file, but I haven\'t been able to figure out how.

I found this sample code in the Swift\'s iBook, but I still don\'t kno

21条回答
  •  时光说笑
    2020-11-22 00:53

    Swift 3.x - 5.x

    The Best Example is to Create a Local Logfile with an Extension .txt that can visible and show in the "Files App" with current date and Time as a File Name

    just add this code in info.plist enable these two features

      UIFileSharingEnabled
      LSSupportsOpeningDocumentsInPlace
    

    and this Function Below

    var logfileName : String = ""
    
    func getTodayString() -> String{
    
        let date = Date()
        let calender = Calendar.current
        let components = calender.dateComponents([.year,.month,.day,.hour,.minute,.second], from: date)
    
        let year = components.year
        let month = components.month
        let day = components.day
        let hour = components.hour
        let minute = components.minute
        let second = components.second
    
        let today_string = String(year!) + "-" + String(month!) + "-" + String(day!) + "-" + String(hour!)  + "" + String(minute!) + "" +  String(second!)+".txt"
    
        return today_string
    
    }
    
    func LogCreator(){
        logfileName = getTodayString()
    
        print("LogCreator: Logfile Generated Named: \(logfileName)")
    
        let file = logfileName //this is the file. we will write to and read from it
    
        let text = "some text" //just a text
    
        if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
    
            let fileURL = dir.appendingPathComponent(file)
            let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask, true)[0]
            print("LogCreator: The Logs are Stored at location \(documentPath)")
    
    
            //writing
            do {
                try text.write(to: fileURL, atomically: false, encoding: .utf8)
            }
            catch {/* error handling here */}
    
            //reading
            do {
                let text2 = try String(contentsOf: fileURL, encoding: .utf8)
                print("LogCreator: The Detail log are :-\(text2)")
            }
            catch {/* error handling here */}
        }
    }
    
    
      [1]: https://i.stack.imgur.com/4eg12.png
    

提交回复
热议问题