2014-02-07 3 views
4

URL에서 텍스트 파일을 복사하고 내 응용 프로그램의 문서 폴더에 저장/덮어 쓰고 데이터 변수로 다시 읽어야합니다. 나는 다음과 같은 코드가 있습니다 : 그것은 구축하고 좋은 방법을 준수하지만 난 내 문서 폴더에있는 text.txt 파일을 만든 다음 내 데이터 변수에 아무것도 통과 할 수URL에서 문서 폴더로 파일을 복사하는 방법은 무엇입니까?

NSData *data; 

//get docsDir 
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *docsDir=[paths objectAtIndex:0]; 

//get path to text.txt 
NSString *filePath=[docsDir stringByAppendingPathComponent:@"text.txt"]; 

//copy file 
NSFileManager *fileManager = [NSFileManager defaultManager]; 
NSError *error; 

if([fileManager fileExistsAtPath:filePath]==YES){ 
    [fileManager removeItemAtPath:filePath error:&error]; 
} 

NSString *urlText = @"http://www.abc.com/text.txt"; 

if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) 
{ 
    NSFileManager *fileManager=[NSFileManager defaultManager]; 
    [fileManager copyItemAtPath:urlText toPath:filePath error:NULL]; 
} 

//Load from file 
NSString *myString=[[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL]; 

//convert string to data 
data=[myString dataUsingEncoding:NSUTF8StringEncoding]; 

. 저는 IOS와 Xcode의 초보자입니다. 모든 단서는 높이 평가 될 것입니다. 감사!!

답변

2

NSFileManager를가 로컬 경로를 처리 할 수 ​​WriteToFile를 사용해야합니다. URL을 주면 아무 도움이되지 않습니다.

copyItemAtPath:toPath:error:은 오류 매개 변수를 취합니다. 다음과 같이 그것을 사용 : 당신은이 오류를 얻을 것

NSError *error; 
if (![fileManager copyItemAtPath:urlText toPath:filePath error:&error]) { 
    NSLog(@"Error %@", error); 
} 

: 유효한 경로가 아닙니다 때문에

Error Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be 
completed. (Cocoa error 260.)" UserInfo=0x9a83c00 {NSFilePath=http://www.abc.com/text.txt, 
NSUnderlyingError=0x9a83b80 "The operation couldn’t be completed. 
No such file or directory"} 

그것은, http://www.abc.com/text.txt에서 파일을 읽을 수 없습니다.


샤는 설명없이 언급 한 바와 같이 써니 먼저 URL에서 객체를 가져 있습니다

NSString *urlText = @"http://www.abc.com/text.txt"; 

if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) 
{ 
    NSURL *url = [NSURL URLWithString:urlText]; 
    NSError *error; 
    NSData *data = [[NSData alloc] initWithContentsOfURL:url options:0 error:&error]; 
    if (!data) { // check if download has failed 
     NSLog(@"Error fetching file %@", error); 
    } 
    else { 
     // successful download 
     if (![data writeToFile:filePath options:NSDataWritingAtomic error:&error]) { // check if writing failed 
      NSLog(@"Error writing file %@", error); 
     } 
     else { 
      NSLog(@"File saved."); 
     } 
    } 
} 

항상 오류를 확인!

+0

을 검토하십시오. Matthias와 Sunny 모두에게 감사합니다. 나는이 며칠 동안 이미 일해왔다! 게다가 내 Xcode 디버그 콘솔에 아무 것도 표시되지 않습니다. 왜 그런지 모르겠다. .. –

1

당신은 URL에서 데이터를 얻을

NSData *urlData = [NSData dataWithContentsOfURL: [NSURL URLWithString:urlText]]; 
    [urlData writeToFile:filePath atomically:YES]; 
+0

감사합니다. 시도해 봤지만 "urlText"는 dataWithContentsOfURL과 함께 사용할 NSURL 유형이 필요하므로 호환되지 않습니다. 다음과 같이 변경되었지만 여전히 작동하지 않습니다. NSData * urlData = [NSData dataWithContentsOfFile : urlText]; [urlData writeToFile : 파일 경로가 원자 적으로 : 예]; –

+0

urlText (string)을 url로 변환해야합니다. 대답 –

관련 문제