your programing

iOS 다운로드 및 앱 내 이미지 저장

lovepro 2020. 10. 13. 08:22
반응형

iOS 다운로드 및 앱 내 이미지 저장


웹 사이트에서 이미지를 다운로드하여 내 앱에 영구적으로 저장할 수 있습니까? 정말 모르겠지만 내 앱에 좋은 기능이 될 것입니다.


캐싱이있는 비동기 다운로드 이미지

캐싱이있는 비동기 다운로드 이미지

백그라운드에서 이미지를 다운로드하는 데 사용할 수있는 저장소가 하나 더 있습니다.


여기에있는 다른 답변이 작동하는 것은 사실이지만 실제로는 프로덕션 코드에서 사용해야하는 솔루션이 아닙니다 . (적어도 수정 없이는)

문제점

이 답변의 문제점은 그대로 구현되고 백그라운드 스레드에서 호출되지 않으면 이미지를 다운로드하고 저장하는 동안 주 스레드를 차단한다는 것입니다. 이것은 나쁘다 .

메인 스레드가 차단되면 이미지 다운로드 / 저장이 완료 될 때까지 UI 업데이트가 발생하지 않습니다. 이것이 의미하는 바의 예로, 다음과 같은 대략적인 제어 흐름을 사용하여 다운로드가 아직 진행 중임을 사용자에게 보여주기 위해 앱에 UIActivityIndicatorView를 추가한다고 가정합니다 (이 답변 전체에서 이것을 예제로 사용하겠습니다).

  1. 다운로드 시작을 담당하는 개체가로드됩니다.
  2. 활동 표시기에 애니메이션을 시작하도록 지시하십시오.
  3. 다음을 사용하여 동기 다운로드 프로세스를 시작합니다. +[NSData dataWithContentsOfURL:]
  4. 방금 다운로드 한 데이터 (이미지)를 저장합니다.
  5. 애니메이션을 중지하도록 활동 표시기에 알립니다.

이제 이것은 합리적인 제어 흐름처럼 보일 수 있지만 심각한 문제를 가장하고 있습니다.

기본 (UI) 스레드에서 활동 표시기의 startAnimating 메서드를 호출하면 다음 번에 기본 실행 루프가 업데이트 될 때까지이 이벤트에 대한 UI 업데이트가 실제로 발생하지 않으며 여기에서 첫 번째 주요 문제가 발생합니다.

이 업데이트가 발생하기 전에 다운로드가 트리거되고 이것은 동기 작업이므로 다운로드가 완료 될 때까지 주 스레드를 차단합니다 (저장에도 동일한 문제가 있음). 이것은 실제로 활동 표시기가 애니메이션을 시작하지 못하게합니다. 그 후 활동 표시기의 stopAnimating 메서드를 호출하고 모든 것이 좋을 것으로 기대하지만 그렇지 않습니다.

이 시점에서 아마도 다음을 궁금해 할 것입니다.

내 활동 표시기가 나타나지 않는 이유는 무엇입니까?

음, 이렇게 생각해보세요. 표시기에 시작하라고 지시했지만 다운로드가 시작되기 전에는 기회가 없습니다. 다운로드가 완료된 후 표시기에 애니메이션을 중지하도록 지시합니다. 메인 스레드가 전체 작업을 통해 차단되었으므로 실제로 표시되는 동작은 표시기에 시작을 알리고 그 사이에 (아마도) 큰 다운로드 작업이 있더라도 즉시 중지하도록 지시하는 선을 따라 더 많이 나타납니다.

이제 최상의 시나리오 에서이 모든 작업은 사용자 경험을 저하시키는 것입니다 (여전히 정말 좋지 않습니다). 작은 이미지 만 다운로드하고 다운로드가 거의 즉시 이루어지기 때문에 이것이 큰 문제가 아니라고 생각하더라도 항상 그런 것은 아닙니다. 일부 사용자는 인터넷 연결이 느리거나 서버 측에서 다운로드가 즉시 시작되지 않도록하는 문제가있을 수 있습니다.

이 두 경우 모두 앱은 UI 업데이트를 처리 할 수 ​​없으며 다운로드 작업이 다운로드가 완료 될 때까지 또는 서버가 요청에 응답 할 때까지 엄지 손가락을 돌리고있는 동안 이벤트를 터치 할 수도 없습니다.

이것이 의미하는 바는 메인 스레드에서 동 기적으로 다운로드하면 다운로드가 현재 진행 중임을 사용자에게 알리는 어떤 것도 구현할 수 없다는 것입니다. 그리고 터치 이벤트는 메인 스레드에서도 처리되기 때문에 모든 종류의 취소 버튼을 추가 할 가능성도 없습니다.

그런 다음 최악의 시나리오 에서 다음과 같은 오류 보고서를 받기 시작합니다.

예외 유형 : 00000020 예외 코드 : 0x8badf00d

예외 코드로 쉽게 식별 0x8badf00d할 수 있으며, "먹은 음식"으로 읽을 수 있습니다. 이 예외는 메인 스레드를 차단하는 장기 실행 작업을 감시하고 이것이 너무 오래 지속되면 문제가되는 앱을 종료하는 워치 독 타이머에 의해 발생합니다. 논란의 여지가 있지만 여전히 사용자 경험이 좋지 않은 문제이지만 이것이 발생하기 시작하면 앱이 나쁜 사용자 경험과 끔찍한 사용자 경험 사이의 경계를 넘은 것입니다.

다음 은 동기식 네트워킹에 대한 Apple의 기술 Q & A (간결성을 위해 줄임) 에서이 문제가 발생하는 원인에 대한 추가 정보입니다 .

네트워크 애플리케이션에서 워치 독 시간 초과 충돌의 가장 일반적인 원인은 주 스레드의 동기 네트워킹입니다. 여기에는 네 가지 요인이 있습니다.

  1. 동기식 네트워킹 — 네트워크 요청을하고 응답을 기다리는 것을 차단하는 곳입니다.
  2. 주 스레드 — 동기식 네트워킹은 일반적으로 이상적이지 않지만 주 스레드에서 수행하면 특정 문제가 발생합니다. 메인 스레드는 사용자 인터페이스 실행을 담당합니다. 상당한 시간 동안 주 스레드를 차단하면 사용자 인터페이스가 허용 할 수 없을 정도로 응답하지 않게됩니다.
  3. 긴 시간 초과 — 네트워크가 그냥 사라지면 (예 : 사용자가 터널로가는 기차에있는 경우) 대기중인 네트워크 요청은 시간 초과가 만료 될 때까지 실패하지 않습니다 ....

...

  1. watchdog — 사용자 인터페이스의 응답 성을 유지하기 위해 iOS에는 감시 메커니즘이 포함되어 있습니다. 애플리케이션이 특정 사용자 인터페이스 이벤트 (시작, 일시 중지, 재개, 종료)에 제 시간에 응답하지 못하면 워치 독이 애플리케이션을 종료하고 워치 독 시간 초과 충돌 보고서를 생성합니다. 워치 독이 제공하는 시간은 공식적으로 문서화되어 있지 않지만 항상 네트워크 시간 초과보다 적습니다.

이 문제의 까다로운 측면 중 하나는 네트워크 환경에 크게 의존한다는 것입니다. 네트워크 연결이 좋은 사무실에서 항상 응용 프로그램을 테스트하는 경우 이러한 유형의 충돌이 발생하지 않습니다. 그러나 애플리케이션을 모든 종류의 네트워크 환경에서 실행할 최종 사용자에게 배포하기 시작하면 이와 같은 충돌이 흔해질 것입니다.

이제이 시점에서 제공된 답변이 문제가 될 수있는 이유에 대해 더 이상 이야기하지 않고 몇 가지 대체 솔루션을 제공하기 시작할 것입니다. 이 예제에서는 작은 이미지의 URL을 사용했으며 더 높은 해상도 이미지를 사용할 때 더 큰 차이를 알 수 있습니다.


솔루션

UI 업데이트를 처리하는 방법을 추가하여 다른 답변의 안전한 버전을 보여주는 것으로 시작하겠습니다. 이것은 몇 가지 예제 중 첫 번째가 될 것이며, 모두 구현 된 클래스에 UIImageView, UIActivityIndicatorView 및 documentsDirectoryURL문서 디렉토리에 액세스하는 방법에 대한 유효한 속성이 있다고 가정합니다 . 프로덕션 코드에서는 더 나은 코드 재사용을 위해 NSURL의 카테고리로 문서 디렉토리에 액세스하는 고유 한 방법을 구현할 수 있지만 이러한 예에서는 괜찮습니다.

- (NSURL *)documentsDirectoryURL
{
    NSError *error = nil;
    NSURL *url = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory
                                                        inDomain:NSUserDomainMask
                                               appropriateForURL:nil
                                                          create:NO
                                                           error:&error];
    if (error) {
        // Figure out what went wrong and handle the error.
    }

    return url;
}

이 예제는 또한 시작하는 스레드가 기본 스레드라고 가정합니다. 이것은 다른 비동기 작업의 콜백 블록과 같은 곳에서 다운로드 작업을 시작하지 않는 한 기본 동작 일 수 있습니다. 보기 컨트롤러의 수명주기 메서드 (예 : viewDidLoad, viewWillAppear : 등)와 같은 일반적인 위치에서 다운로드를 시작하면 예상되는 동작이 생성됩니다.

이 첫 번째 예에서는 +[NSData dataWithContentsOfURL:]방법 을 사용 하지만 몇 가지 주요 차이점이 있습니다. 우선,이 예제에서 우리가하는 첫 번째 호출은 활동 표시기에 애니메이션을 시작하도록 지시하는 것입니다. 그러면이 예제와 동기 예제간에 즉각적인 차이가 있습니다. 즉시 dispatch_async ()를 사용하여 전역 동시 대기열을 전달하여 실행을 백그라운드 스레드로 이동합니다.

이 시점에서 이미 다운로드 작업을 크게 개선했습니다. dispatch_async () 블록 내의 모든 것이 이제 메인 스레드에서 발생하므로 인터페이스가 더 이상 잠기지 않으며 앱이 터치 이벤트에 자유롭게 응답 할 수 있습니다.

여기서 주목해야 할 점은이 블록 내의 모든 코드가 이미지 다운로드 / 저장이 성공한 지점까지 백그라운드 스레드에서 실행된다는 것입니다.이 지점에서 활동 표시기에 stopAnimating을 지시 할 수 있습니다 또는 새로 저장된 이미지를 UIImageView에 적용합니다. 어느 쪽이든 UI에 대한 업데이트이므로 dispatch_get_main_queue ()를 사용하여 메인 스레드를 다시 디스패치하여 수행해야합니다. 그렇게하지 않으면 정의되지 않은 동작이 발생하여 예상치 못한 시간 후에 UI가 업데이트되거나 충돌이 발생할 수도 있습니다. UI 업데이트를 수행하기 전에 항상 메인 스레드로 돌아 가야합니다.

// Start the activity indicator before moving off the main thread
[self.activityIndicator startAnimating];
// Move off the main thread to start our blocking tasks.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Create the image URL from a known string.
    NSURL *imageURL = [NSURL URLWithString:@"http://www.google.com/images/srpr/logo3w.png"];

    NSError *downloadError = nil;
    // Create an NSData object from the contents of the given URL.
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL
                                              options:kNilOptions
                                                error:&downloadError];
    // ALWAYS utilize the error parameter!
    if (downloadError) {
        // Something went wrong downloading the image. Figure out what went wrong and handle the error.
        // Don't forget to return to the main thread if you plan on doing UI updates here as well.
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.activityIndicator stopAnimating];
            NSLog(@"%@",[downloadError localizedDescription]);
        });
    } else {
        // Get the path of the application's documents directory.
        NSURL *documentsDirectoryURL = [self documentsDirectoryURL];
        // Append the desired file name to the documents directory path.
        NSURL *saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:@"GCD.png"];

        NSError *saveError = nil;
        BOOL writeWasSuccessful = [imageData writeToURL:saveLocation
                                                options:kNilOptions
                                                  error:&saveError];
        // Successful or not we need to stop the activity indicator, so switch back the the main thread.
        dispatch_async(dispatch_get_main_queue(), ^{
            // Now that we're back on the main thread, you can make changes to the UI.
            // This is where you might display the saved image in some image view, or
            // stop the activity indicator.

            // Check if saving the file was successful, once again, utilizing the error parameter.
            if (writeWasSuccessful) {
                // Get the saved image data from the file.
                NSData *imageData = [NSData dataWithContentsOfURL:saveLocation];
                // Set the imageView's image to the image we just saved.
                self.imageView.image = [UIImage imageWithData:imageData];
            } else {
                NSLog(@"%@",[saveError localizedDescription]);
                // Something went wrong saving the file. Figure out what went wrong and handle the error.
            }

            [self.activityIndicator stopAnimating];
        });
    }
});

이제 위에 표시된 방법은 조기에 취소 할 수 없다는 점을 고려할 때 이상적인 솔루션이 아니라는 점을 명심 하십시오. 다운로드 진행 상황을 표시하지 않으며 어떤 종류의 인증 문제도 처리 할 수 ​​없습니다. 특정 시간 초과 간격 등이 제공되지 않습니다 (많은 이유). 아래에서 몇 가지 더 나은 옵션을 다룰 것입니다.

이 예제에서는 iOS 7 이상을 대상으로하는 앱에 대한 솔루션 만 다룰 것입니다 (작성 당시) iOS 8이 현재 주요 릴리스이고 Apple은 버전 N 및 N-1 지원 만 제안하고 있습니다 . 이전 iOS 버전을 지원해야하는 경우 NSURLConnection 클래스 와 AFNetworking 1.0 버전을 살펴 보는 것이 좋습니다 . 이 답변의 개정 내역을 보면 NSURLConnection 및 ASIHTTPRequest를 사용하는 기본 예제를 찾을 수 있지만 ASIHTTPRequest는 더 이상 유지되지 않으며 새 프로젝트에 사용 해서는 안됩니다 .


NSURLSession

iOS 7에 도입 된 NSURLSession으로 시작하여 iOS에서 네트워킹을 수행 할 수있는 용이성을 크게 향상시킵니다. NSURLSession을 사용하면 콜백 블록으로 비동기 HTTP 요청을 쉽게 수행하고 위임으로 인증 문제를 처리 할 수 ​​있습니다. 그러나이 클래스를 정말 특별하게 만드는 것은 응용 프로그램이 백그라운드로 전송되거나 종료되거나 충돌하더라도 다운로드 작업을 계속 실행할 수 있다는 것입니다. 다음은 사용의 기본 예입니다.

// Start the activity indicator before starting the download task.
[self.activityIndicator startAnimating];

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
// Use a session with a custom configuration
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
// Create the image URL from some known string.
NSURL *imageURL = [NSURL URLWithString:@"http://www.google.com/images/srpr/logo3w.png"];
// Create the download task passing in the URL of the image.
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:imageURL completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
    // Get information about the response if neccessary.
    if (error) {
        NSLog(@"%@",[error localizedDescription]);
        // Something went wrong downloading the image. Figure out what went wrong and handle the error.
        // Don't forget to return to the main thread if you plan on doing UI updates here as well.
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.activityIndicator stopAnimating];
        });
    } else {
        NSError *openDataError = nil;
        NSData *downloadedData = [NSData dataWithContentsOfURL:location
                                                       options:kNilOptions
                                                         error:&openDataError];
        if (openDataError) {
            // Something went wrong opening the downloaded data. Figure out what went wrong and handle the error.
            // Don't forget to return to the main thread if you plan on doing UI updates here as well.
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"%@",[openDataError localizedDescription]);
                [self.activityIndicator stopAnimating];
            });
        } else {
            // Get the path of the application's documents directory.
            NSURL *documentsDirectoryURL = [self documentsDirectoryURL];
            // Append the desired file name to the documents directory path.
            NSURL *saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:@"NSURLSession.png"];
            NSError *saveError = nil;

            BOOL writeWasSuccessful = [downloadedData writeToURL:saveLocation
                                                          options:kNilOptions
                                                            error:&saveError];
            // Successful or not we need to stop the activity indicator, so switch back the the main thread.
            dispatch_async(dispatch_get_main_queue(), ^{
                // Now that we're back on the main thread, you can make changes to the UI.
                // This is where you might display the saved image in some image view, or
                // stop the activity indicator.

                // Check if saving the file was successful, once again, utilizing the error parameter.
                if (writeWasSuccessful) {
                    // Get the saved image data from the file.
                    NSData *imageData = [NSData dataWithContentsOfURL:saveLocation];
                    // Set the imageView's image to the image we just saved.
                    self.imageView.image = [UIImage imageWithData:imageData];
                } else {
                    NSLog(@"%@",[saveError localizedDescription]);
                    // Something went wrong saving the file. Figure out what went wrong and handle the error.
                }

                [self.activityIndicator stopAnimating];
            });
        }
    }
}];

// Tell the download task to resume (start).
[task resume];

여기에서 downloadTaskWithURL: completionHandler:메서드 -[NSURLSessionTask resume]인스턴스 메서드 가 호출 되는 NSURLSessionDownloadTask의 인스턴스를 반환 한다는 것을 알 수 있습니다. 이것은 실제로 다운로드 작업을 시작하도록 지시하는 방법입니다. 즉, 다운로드 작업을 시작하고 원하는 경우 시작을 보류 할 수 있습니다 (필요한 경우). 이것은 또한 작업에 대한 참조를 저장하는 한 해당 cancelsuspend메서드를 사용하여 필요한 경우 작업을 취소하거나 일시 중지 할 수도 있음을 의미합니다.

NSURLSessionTasks의 정말 멋진 점은 약간의 KVO 로 countOfBytesExpectedToReceive 및 countOfBytesReceived 속성의 값을 모니터링하고, 이러한 값을 NSByteCountFormatter 에 제공하고, 사람이 읽을 수있는 단위 (예 : 42)로 사용자에게 다운로드 진행률 표시기를 쉽게 만들 수 있다는 것입니다. 100KB 중 KB).

하지만 NSURLSession에서 벗어나기 전에 다운로드 콜백 블록의 여러 지점에서 주 스레드로 다시 dispatch_async해야하는 추악함을 피할 수 있다는 점을 지적하고 싶습니다. 이 경로로 이동하도록 선택한 경우 델리게이트 대기열뿐만 아니라 델리게이트를 지정할 수있는 이니셜 라이저로 세션을 초기화 할 수 있습니다. 이렇게하려면 콜백 블록 대신 델리게이트 패턴을 사용해야하지만 백그라운드 다운로드를 지원하는 유일한 방법이기 때문에 유용 할 수 있습니다.

NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration
                                                      delegate:self
                                                 delegateQueue:[NSOperationQueue mainQueue]];

AFNetworking 2.0

AFNetworking에 대해 들어 본 적이 없다면 IMHO가 모든 네트워킹 라이브러리입니다. Objective-C 용으로 생성되었지만 Swift에서도 작동합니다. 저자의 말 :

AFNetworking은 iOS 및 Mac OS X를위한 유쾌한 네트워킹 라이브러리입니다. Foundation URL Loading System 위에 구축되어 Cocoa에 구축 된 강력한 고급 네트워킹 추상화를 확장합니다. 사용하기 좋은 잘 설계된 기능이 풍부한 API를 갖춘 모듈 식 아키텍처가 있습니다.

AFNetworking 2.0은 iOS 6 이상을 지원하지만이 예제에서는 NSURLSession 클래스 주변의 모든 새 API를 사용하므로 iOS 7 이상이 필요한 AFHTTPSessionManager 클래스를 사용합니다. 위의 NSURLSession 예제와 많은 코드를 공유하는 아래 예제를 읽으면 이것은 분명해질 것입니다.

그래도 지적하고 싶은 몇 가지 차이점이 있습니다. 시작하려면 자체 NSURLSession을 만드는 대신 내부적으로 NSURLSession을 관리하는 AFURLSessionManager의 인스턴스를 만듭니다. 이렇게하면와 같은 편리한 방법 중 일부를 활용할 수 있습니다 -[AFURLSessionManager downloadTaskWithRequest:progress:destination:completionHandler:]. 이 방법의 흥미로운 점은 주어진 대상 파일 경로, 완료 블록 및 다운로드 진행률에 대한 정보를 관찰 할 수 있는 NSProgress 포인터에 대한 입력으로 다운로드 작업을 상당히 간결하게 만들 수 있다는 것 입니다. 여기에 예가 있습니다.

// Use the default session configuration for the manager (background downloads must use the delegate APIs)
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
// Use AFNetworking's NSURLSessionManager to manage a NSURLSession.
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

// Create the image URL from some known string.
NSURL *imageURL = [NSURL URLWithString:@"http://www.google.com/images/srpr/logo3w.png"];
// Create a request object for the given URL.
NSURLRequest *request = [NSURLRequest requestWithURL:imageURL];
// Create a pointer for a NSProgress object to be used to determining download progress.
NSProgress *progress = nil;

// Create the callback block responsible for determining the location to save the downloaded file to.
NSURL *(^destinationBlock)(NSURL *targetPath, NSURLResponse *response) = ^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    // Get the path of the application's documents directory.
    NSURL *documentsDirectoryURL = [self documentsDirectoryURL];
    NSURL *saveLocation = nil;

    // Check if the response contains a suggested file name
    if (response.suggestedFilename) {
        // Append the suggested file name to the documents directory path.
        saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:response.suggestedFilename];
    } else {
        // Append the desired file name to the documents directory path.
        saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:@"AFNetworking.png"];
    }

    return saveLocation;
};

// Create the completion block that will be called when the image is done downloading/saving.
void (^completionBlock)(NSURLResponse *response, NSURL *filePath, NSError *error) = ^void (NSURLResponse *response, NSURL *filePath, NSError *error) {
    dispatch_async(dispatch_get_main_queue(), ^{
        // There is no longer any reason to observe progress, the download has finished or cancelled.
        [progress removeObserver:self
                      forKeyPath:NSStringFromSelector(@selector(fractionCompleted))];

        if (error) {
            NSLog(@"%@",error.localizedDescription);
            // Something went wrong downloading or saving the file. Figure out what went wrong and handle the error.
        } else {
            // Get the data for the image we just saved.
            NSData *imageData = [NSData dataWithContentsOfURL:filePath];
            // Get a UIImage object from the image data.
            self.imageView.image = [UIImage imageWithData:imageData];
        }
    });
};

// Create the download task for the image.
NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request
                                                         progress:&progress
                                                      destination:destinationBlock
                                                completionHandler:completionBlock];
// Start the download task.
[task resume];

// Begin observing changes to the download task's progress to display to the user.
[progress addObserver:self
           forKeyPath:NSStringFromSelector(@selector(fractionCompleted))
              options:NSKeyValueObservingOptionNew
              context:NULL];

물론 NSProgress 인스턴스의 속성 중 하나에 관찰자로이 코드를 포함하는 클래스를 추가 했으므로 -[NSObject observeValueForKeyPath:ofObject:change:context:]메서드 를 구현해야 합니다. 이 경우 다운로드 진행률을 표시하기 위해 진행률 레이블을 업데이트하는 방법에 대한 예를 포함했습니다. 정말 쉽습니다. NSProgress에는 localizedDescription지역화 된 사람이 읽을 수있는 형식으로 진행 정보를 표시 하는 인스턴스 메서드 가 있습니다.

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    // We only care about updates to fractionCompleted
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(fractionCompleted))]) {
        NSProgress *progress = (NSProgress *)object;
        // localizedDescription gives a string appropriate for display to the user, i.e. "42% completed"
        self.progressLabel.text = progress.localizedDescription;
    } else {
        [super observeValueForKeyPath:keyPath
                             ofObject:object
                               change:change
                              context:context];
    }
}

프로젝트에서 AFNetworking을 사용하려는 경우, 당신이 따라야합니다, 잊지 마세요 설치 지침을 다시 확인 할 수 #import <AFNetworking/AFNetworking.h>.

Alamofire

마지막으로 Alamofire 를 사용하여 마지막 예를 들겠습니다 . 이것은 Swift의 네트워킹을 케이크 산책으로 만드는 라이브러리입니다. 이 샘플의 내용에 대해 자세히 설명하기에는 문자가 부족하지만 마지막 예제와 거의 동일한 작업을 수행합니다.

// Create the destination closure to pass to the download request. I haven't done anything with them
// here but you can utilize the parameters to make adjustments to the file name if neccessary.
let destination = { (url: NSURL!, response: NSHTTPURLResponse!) -> NSURL in
    var error: NSError?
    // Get the documents directory
    let documentsDirectory = NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory,
        inDomain: .UserDomainMask,
        appropriateForURL: nil,
        create: false,
        error: &error
    )

    if let error = error {
        // This could be bad. Make sure you have a backup plan for where to save the image.
        println("\(error.localizedDescription)")
    }

    // Return a destination of .../Documents/Alamofire.png
    return documentsDirectory!.URLByAppendingPathComponent("Alamofire.png")
}

Alamofire.download(.GET, "http://www.google.com/images/srpr/logo3w.png", destination)
    .validate(statusCode: 200..<299) // Require the HTTP status code to be in the Successful range.
    .validate(contentType: ["image/png"]) // Require the content type to be image/png.
    .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
        // Create an NSProgress object to represent the progress of the download for the user.
        let progress = NSProgress(totalUnitCount: totalBytesExpectedToRead)
        progress.completedUnitCount = totalBytesRead

        dispatch_async(dispatch_get_main_queue()) {
            // Move back to the main thread and update some progress label to show the user the download is in progress.
            self.progressLabel.text = progress.localizedDescription
        }
    }
    .response { (request, response, _, error) in
        if error != nil {
            // Something went wrong. Handle the error.
        } else {
            // Open the newly saved image data.
            if let imageData = NSData(contentsOfURL: destination(nil, nil)) {
                dispatch_async(dispatch_get_main_queue()) {
                    // Move back to the main thread and add the image to your image view.
                    self.imageView.image = UIImage(data: imageData)
                }
            }
        }
    }

앱 번들 내에는 아무것도 저장할 수 없지만 +[NSData dataWithContentsOfURL:]앱의 문서 디렉토리에 이미지를 저장하는 데 사용할 수 있습니다 . 예 :

NSData *imageData = [NSData dataWithContentsOfURL:myImageURL];
NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"/myImage.png"];
[imageData writeToFile:imagePath atomically:YES];

정확히 영구적 인 것은 아니지만 최소한 사용자가 앱을 삭제할 때까지 유지됩니다.


그것이 주요 개념입니다. 재미있게 보내세요;)

NSURL *url = [NSURL URLWithString:@"http://example.com/yourImage.png"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
path = [path stringByAppendingString:@"/yourLocalImage.png"];
[data writeToFile:path atomically:YES];

현재 IO5에 있기 때문에 더 이상 디스크에 이미지를 쓸 필요가 없습니다.
이제 coredata 바이너리 속성에 "외부 저장소 허용"을 설정할 수 있습니다. 사과 릴리스 노트에 따르면 다음을 의미합니다.

이미지 썸네일과 같은 작은 데이터 값은 데이터베이스에 효율적으로 저장할 수 있지만 큰 사진이나 기타 미디어는 파일 시스템에서 직접 처리하는 것이 가장 좋습니다. 이제 관리되는 개체 속성의 값이 외부 레코드로 저장되도록 지정할 수 있습니다. setAllowsExternalBinaryDataStorage를 참조하십시오 . 활성화되면 Core Data는 데이터를 데이터베이스에 직접 저장해야하는지 아니면 URI를 저장해야하는지 값별로 경험적으로 결정합니다. 당신을 위해 관리하는 별도의 파일에. 이 옵션을 사용하면 이진 데이터 속성의 내용을 기반으로 쿼리 할 수 ​​없습니다.


다른 사람들이 말했듯이 사용자 인터페이스를 차단하지 않고 백그라운드 스레드에서 사진을 다운로드해야하는 경우가 많습니다.

이 경우 제가 가장 좋아하는 솔루션은 다음과 같은 블록으로 편리한 방법을 사용하는 것입니다. (credit-> iOS : How To Download Images Asynchronously (And Make Your UITableView Scroll Fast) )

- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               if ( !error )
                               {
                                   UIImage *image = [[UIImage alloc] initWithData:data];
                                   completionBlock(YES,image);
                               } else{
                                   completionBlock(NO,nil);
                               }
                           }];
}

그리고 그것을

NSURL *imageUrl = //...

[[MyUtilManager sharedInstance] downloadImageWithURL:[NSURL URLWithString:imageURL] completionBlock:^(BOOL succeeded, UIImage *image) {
    //Here you can save the image permanently, update UI and do what you want...
}];

광고 배너를 다운로드하는 방법은 다음과 같습니다. 큰 이미지 또는 여러 이미지를 다운로드하는 경우 백그라운드에서 수행하는 것이 가장 좋습니다.

- (void)viewDidLoad {
    [super viewDidLoad];

    [self performSelectorInBackground:@selector(loadImageIntoMemory) withObject:nil];

}
- (void)loadImageIntoMemory {
    NSString *temp_Image_String = [[NSString alloc] initWithFormat:@"http://yourwebsite.com/MyImageName.jpg"];
    NSURL *url_For_Ad_Image = [[NSURL alloc] initWithString:temp_Image_String];
    NSData *data_For_Ad_Image = [[NSData alloc] initWithContentsOfURL:url_For_Ad_Image];
    UIImage *temp_Ad_Image = [[UIImage alloc] initWithData:data_For_Ad_Image];
    [self saveImage:temp_Ad_Image];
    UIImageView *imageViewForAdImages = [[UIImageView alloc] init];
    imageViewForAdImages.frame = CGRectMake(0, 0, 320, 50);
    imageViewForAdImages.image = [self loadImage];
    [self.view addSubview:imageViewForAdImages];
}
- (void)saveImage: (UIImage*)image {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* path = [documentsDirectory stringByAppendingPathComponent: @"MyImageName.jpg" ];
    NSData* data = UIImagePNGRepresentation(image);
    [data writeToFile:path atomically:YES];
}
- (UIImage*)loadImage {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* path = [documentsDirectory stringByAppendingPathComponent:@"MyImageName.jpg" ];
    UIImage* image = [UIImage imageWithContentsOfFile:path];
    return image;
}

다음은 URL에서 비동기식으로 이미지를 다운로드 한 다음 Objective-c :->에서 원하는 위치에 저장하는 코드입니다.

    + (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
        {
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
            [NSURLConnection sendAsynchronousRequest:request
                                               queue:[NSOperationQueue mainQueue]
                                   completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                                       if ( !error )
                                       {
                                           UIImage *image = [[UIImage alloc] initWithData:data];
                                           completionBlock(YES,image);
                                       } else{
                                           completionBlock(NO,nil);
                                       }
                                   }];
        }

AFNetworking 라이브러리를 사용하여 이미지를 다운로드하고 해당 이미지가 UITableview에서 사용중인 경우 cellForRowAtIndexPath에서 아래 코드를 사용할 수 있습니다.

 [self setImageWithURL:user.user_ProfilePicturePath toControl:cell.imgView]; 
 
-(void)setImageWithURL:(NSURL*)url toControl:(id)ctrl
{
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request imageProcessingBlock:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
        if (image) {
            if([ctrl isKindOfClass:[UIButton class]])
            {
                UIButton btn =(UIButton)ctrl;
                [btn setBackgroundImage:image forState:UIControlStateNormal];
            }
            else
            {
                UIImageView imgView = (UIImageView)ctrl;
                imgView.image = image;
            }

} } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) { NSLog(@"No Image"); }]; [operation start];}

NSURLSessionDataTask를 사용하면 UI 차단없이 이미지를 다운로드 할 수 있습니다.

+(void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
 {
 NSURLSessionDataTask*  _sessionTask = [[NSURLSession sharedSession] dataTaskWithRequest:[NSURLRequest requestWithURL:url]
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error != nil)
        {
          if ([error code] == NSURLErrorAppTransportSecurityRequiresSecureConnection)
                {
                    completionBlock(NO,nil);
                }
         }
    else
     {
      [[NSOperationQueue mainQueue] addOperationWithBlock: ^{
                        dispatch_async(dispatch_get_main_queue(), ^{
                        UIImage *image = [[UIImage alloc] initWithData:data];
                        completionBlock(YES,image);

                        });

      }];

     }

                                            }];
    [_sessionTask resume];
}

Here is a Swift 5 solution for downloading and saving an image or in general a file to the documents directory by using Alamofire:

func dowloadAndSaveFile(from url: URL) {
    let destination: DownloadRequest.DownloadFileDestination = { _, _ in
        var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        documentsURL.appendPathComponent(url.lastPathComponent)
        return (documentsURL, [.removePreviousFile])
    }
    let request = SessionManager.default.download(url, method: .get, to: destination)
    request.validate().responseData { response in
        switch response.result {
        case .success:
            if let destinationURL = response.destinationURL {
                print(destinationURL)
            }
        case .failure(let error):
            print(error.localizedDescription)
        }
    }
}

참고URL : https://stackoverflow.com/questions/6238139/ios-download-and-save-image-inside-app

반응형