2017-12-06 13 views
0

내 응용 프로그램에서는 saveURL.txt라는 프로그램의 문서 디렉토리에있는 텍스트 파일에 데이터를 추가하여 나중에 호출하고 구문 분석 할 수 있도록하려고합니다. 내가Swift 3 텍스트 파일에 쓰기

let fileName = "saveURL" 
let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) 

let fileURL = DocumentDirURL.appendingPathComponent(fileName).appendingPathExtension("txt") 
print("FilePath: \(fileURL.path)") 

let writeString = "Write this text to the fileURL as text in iOS using Swift" 
do { 
    // Write to the file 
    try writeString.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8) 
    print("past try writeString.write") 
} catch let error as NSError { 
    print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription) 
} 

var readString = "" // Used to store the file contents 
do { 
    // Read the file contents 
    readString = try String(contentsOf: fileURL) 
} catch let error as NSError { 
    print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription) 
} 
print("File Text: \(readString)") 

있는 내 코드를 콘솔에 표시되는 출력은

FilePath를 :/사용자/마이크/라이브러리/개발자/CoreSimulator/디바이스/752A5025-0AA0-4BE1-B70F-644A904F2D8A/데이터/용기/데이터/응용 프로그램/0084AD99-63DB-439F-8427-DDDF161CFAC0/문서/saveURL.txt
지난 writeString.write
파일의 텍스트를보십시오 사용하여 아이폰 OS에서 텍스트로 fileURL이 텍스트를 쓰기 스위프트

실제로 저장되어있는 출력을 표시하고 있지만 실제로 파일에 추가되었는지 확인하기 위해 파일을 검사 할 때 여전히 비어 있습니다. 나는 신속한 파일은 읽기 전용 일 뿐이라고 생각하지만, 프로그램에서 작동하지만 작동하지 않는 예제를 보았습니다.

+0

게시 한 코드의 'print' 문의 실제 출력과 함께 질문을 업데이트하십시오 (코멘트를 게시하지 마십시오). – rmaddy

+0

* "실제로 파일에 추가되었는지 확인하기 위해 파일을 검사 할 때 여전히 비어 있습니다"*는 무엇을 의미합니까? 너는 어떻게 지내니? 비어있는 것은 무엇입니까? – rmaddy

+0

내 프로그램 파일 디렉토리의 saveURL 파일은 너무 분명하게 쓰여지고 있지만 여전히 빈 텍스트 파일입니다. 파일을 확인하고 아무것도 없는지 확인하기 위해 체크 중입니다. – Kolorbox

답변

0

다음은 텍스트 파일에 쓰기 URL 용 코드입니다.

func writeToFile(urlString: String) 
{ 
    let file = "/saveURL.txt" //this is the file. we will write to and read from it 

     if let dir = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true).first { 
     let path = dir + file 
     print(path) 
     do { 
      try urlString.write(toFile: path, atomically: false, encoding: String.Encoding.utf8) 
     } 
     catch {/* error handling here */} 
    } 
} 

희망이 도움이 될 것입니다.

+0

이 함수를 구현하고 저장 버튼을 눌렀을 때 함수에 문자열을 전달하면 호출됩니다. 그것은 성공적으로 호출 할 수 있지만 내 프로그램 내 실제 saveURL.txt 파일을 검사 할 때 거기에 여전히 텍스트가 기록됩니다. – Kolorbox

+0

대답이 'print (path)'를 업데이트했습니다. 해당 경로를 확인하십시오. –

+0

'/ Users/mike/Library/Developer/CoreSimulator/Devices/752A5025-0AA0-4BE1-B70F-644A904F2D8A/data/Containers/Data/Application/A1895394-2AFF-41DE-A174-45F7A8B77258/Documents/saveURL.txt' 인쇄 할 때 무슨 일이 생기는가? – Kolorbox