2011-03-16 6 views

답변

144

나는, 그러나 웹에서 파일을 얻고 로컬로 저장하는 것을 wget을 모르겠어요, 당신이있는 NSData를 사용할 수 있습니다

NSString *stringURL = @"http://www.somewhere.com/thefile.png"; 
NSURL *url = [NSURL URLWithString:stringURL]; 
NSData *urlData = [NSData dataWithContentsOfURL:url]; 
if (urlData) 
{ 
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.png"]; 
    [urlData writeToFile:filePath atomically:YES]; 
} 
+3

그냥 궁금이 차단이 여부 :

는이 기사의 읽기 있나요? 나는 이것이 하나의 블록이라고 가정 할 것이다. – schystz

+6

@schystz 동기를 막음으로써 동시성을 의미한다면 그렇습니다. – carlossless

+0

마찬가지로,'+ [NSString stringWithContentsOfURL : encoding : error :]'에 관심이있을 수도 있습니다. – Zmaster

6

내가 훨씬 더 쉬운 방법이 ASIHTTPRequest를 사용하는 것입니다 생각합니다. 이 작업을 수행 할 수있는 코드의 세 가지 라인 :

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 
[request setDownloadDestinationPath:@"/path/to/my_file.txt"]; 
[request startSynchronous]; 

Link to Reference

UPDATE : 나는 ASIHTTPRequest가 더 이상 유지되는 것을 언급 없습니다. 저자는 특별히 사람들에게 다른 프레임 워크를 대신 사용하도록 권고했습니다. AFNetworking

1

언젠가는 사용하기 쉬운 "다운로드 관리자"라이브러리 인 PTDownloadManager을 구현했습니다. 당신은 그걸 줄 수 있어요!

+0

아주 잘됐다. 감사. –

0

이렇게 많은 방법이 있습니다 :

  1. NSURL

  2. ASIHTTP

  3. libcurl

  4. easyget, 강력한 기능을 가진 상업 하나.

+0

여전히 어딘가에 여전히 지원되는 ASIHTTP입니까? 웹 사이트는 다른 것의 사용을 권고합니다 : http://allseeing-i.com/ASIHTTPRequest/ – Robert

+1

번호 ASIHTTP를 사용하지 마십시오. 높은 수준의 도구 대신 AFNetworking을 사용하십시오. https://github.com/AFNetworking/AFNetworking – GnarlyDog

13

나는 완료 블록을 사용하여 비동기 액세스를 사용할 수 있습니다.

이 예에서는 Google 로고를 장치의 문서 디렉토리에 저장합니다. (아이폰 OS 5+, OSX 10.7) NSURLSession는 아이폰 OS 7에 도입

NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; 
NSString *filePath = [documentDir stringByAppendingPathComponent:@"GoogleLogo.png"]; 

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.google.com/images/srpr/logo11w.png"]]; 
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 
    if (error) { 
     NSLog(@"Download Error:%@",error.description); 
    } 
    if (data) { 
     [data writeToFile:filePath atomically:YES]; 
     NSLog(@"File is saved to %@",filePath); 
    } 
}]; 
11

는 파일을 다운로드의 권장 SDK의 방법입니다. 타사 라이브러리를 가져올 필요가 없습니다.

NSURL *url = [NSURL URLWithString:@"http://www.something.com/file"]; 
NSURLRequest *downloadRequest = [NSURLRequest requestWithURL:url]; 
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; 
NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil]; 
self.downloadTask = [self.urlSession downloadTaskWithRequest:downloadRequest]; 
[self.downloadTask resume]; 

그런 다음 오류, 다운로드 완료, 다운로드 진행 상황 등을 모니터링 할 수 NSURLSessionDownloadDelegate 위임 방법을 사용할 수 있습니다 ... 당신이 선호 너무 경우 인라인 블록 완료 핸들러 콜백 방법이 있습니다. Apples docs는 서로를 사용할 필요가있을 때 설명합니다.

objc.io NSURLConnection to NSURLSession

URL Loading System Programming Guide

+1

이 작업은 비동기 적으로 작동합니까? –

+0

비동기 적으로 작동하지 않는 네트워크 API의 경우 이상합니다. 그렇습니다. NSURLSession API는 매우 비동기 적입니다. https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/UsingNSURLSession.html – bandejapaisa

+0

델리게이트 부분 처리는 성가신 일입니다. –

관련 문제