Objective-C를 처음 사용하고 웹 (웹 서버에서 변경된 경우)에서 파일을 다운로드하고 로컬로 저장하여 응용 프로그램에서 사용할 수 있도록하려고합니다.목표 C를 사용하여 iOS에서 로컬로 파일을 다운로드하고 저장하려면 어떻게해야합니까?
주로 구현하고 싶은 것은 wget --timestamp <url>
입니다.
Objective-C를 처음 사용하고 웹 (웹 서버에서 변경된 경우)에서 파일을 다운로드하고 로컬로 저장하여 응용 프로그램에서 사용할 수 있도록하려고합니다.목표 C를 사용하여 iOS에서 로컬로 파일을 다운로드하고 저장하려면 어떻게해야합니까?
주로 구현하고 싶은 것은 wget --timestamp <url>
입니다.
나는, 그러나 웹에서 파일을 얻고 로컬로 저장하는 것을 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];
}
내가 훨씬 더 쉬운 방법이 ASIHTTPRequest를 사용하는 것입니다 생각합니다. 이 작업을 수행 할 수있는 코드의 세 가지 라인 :
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:@"/path/to/my_file.txt"];
[request startSynchronous];
UPDATE : 나는 ASIHTTPRequest가 더 이상 유지되는 것을 언급 없습니다. 저자는 특별히 사람들에게 다른 프레임 워크를 대신 사용하도록 권고했습니다. AFNetworking
나는 완료 블록을 사용하여 비동기 액세스를 사용할 수 있습니다.
이 예에서는 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);
}
}];
는 파일을 다운로드의 권장 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는 서로를 사용할 필요가있을 때 설명합니다.
이 작업은 비동기 적으로 작동합니까? –
비동기 적으로 작동하지 않는 네트워크 API의 경우 이상합니다. 그렇습니다. NSURLSession API는 매우 비동기 적입니다. https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/UsingNSURLSession.html – bandejapaisa
델리게이트 부분 처리는 성가신 일입니다. –
그냥 궁금이 차단이 여부 :
는이 기사의 읽기 있나요? 나는 이것이 하나의 블록이라고 가정 할 것이다. – schystz
@schystz 동기를 막음으로써 동시성을 의미한다면 그렇습니다. – carlossless
마찬가지로,'+ [NSString stringWithContentsOfURL : encoding : error :]'에 관심이있을 수도 있습니다. – Zmaster