2012-06-15 3 views
11

내 앱에서 버튼을 클릭하면 로그 파일에 쓰고 싶습니다. UITextView 내 데이터를 표시하고 싶습니다. UITextView를 토글하는 방법을 알고 있지만 로컬 파일 시스템에서 로그 파일을 작성하고 업데이트하는 방법을 알지 못합니다. 어떤 도움을 주셔서 감사합니다.iOS 앱에서 로그 파일 만들기

답변

32

기본 아이디어는 파일을 만들고 새 줄을 기록 할 때마다 추가한다는 것입니다.

파일에 쓰기 : 당신은 다음과 같이 아주 쉽게 그것을 할 수

NSString *content = @"This is my log"; 

//Get the file path 
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:@"myFileName.txt"]; 

//create file if it doesn't exist 
if(![[NSFileManager defaultManager] fileExistsAtPath:fileName]) 
    [[NSFileManager defaultManager] createFileAtPath:fileName contents:nil attributes:nil]; 

//append text to file (you'll probably want to add a newline every write) 
NSFileHandle *file = [NSFileHandle fileHandleForUpdatingAtPath:fileName]; 
[file seekToEndOfFile]; 
[file writeData:[content dataUsingEncoding:NSUTF8StringEncoding]]; 
[file closeFile]; 

읽기 : 나는 거기에 클래스가 자동으로 생성 운 이후로 이렇게라고 생각

//get file path 
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:@"myFileName.txt"]; 

//read the whole file as a single string 
NSString *content = [NSString stringWithContentsOfFile:fileName encoding:NSUTF8StringEncoding error:nil]; 
+0

그것은 좋아하지 않는는 '[NSFileHandle fileHandleForUpdatingAtPath는 : logPath에]'logPath'이 선언되지 않은 식별자를 사용한다는 것이다. 그것을 명확히 할 수 있겠습니까? –

+0

나쁘다 - logPath를 fileName으로 대체하십시오. 잘못된 변수. – CrimsonDiego

+1

감사합니다. 당신이 말한 모든 일을했지만, UITextView에 데이터를 추가하고 싶을 때,'logFile.text = [NSString stringWithContentsOfFile : fileName encoding : NSUTF8StringEncoding error : nil];'아무 것도 나타나지 않았습니다. 디버깅을 한 후 로그 파일 자체가 null 인 것을 확인했습니다. 왜 그런지 알고 있니? –

1

내 자신의.

NSLogger는 iOS 버전 3.0 이상을위한 경량 클래스입니다. 개발자는 .txt 파일로 로컬에 저장된 여러 가지 '이벤트'를 쉽게 기록 할 수 있습니다.

https://github.com/northernspark/NSLogger