簡體   English   中英

iOS下載批量圖像的最佳方法

[英]iOS best way to download bulk images

在我的應用中,打開ViewController時必須下載近500張圖像。 一次下載所有500張圖像不是一個正確的主意。 我想一次保留5個活動的異步下載。 五分之一的任務完成后,應從下一個開始。

我還有一個刷新控件,它將從頭開始重新下載所有圖像。

我可以選擇哪種技術來實現此模式?

到目前為止,這是我嘗試過的

在屬性聲明中創建信號量

private var semaphore = dispatch_semaphore_create(5)

收到網絡服務響應后,

private func startDownloadingImages() {
        for place in places {
            dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER)
            self.downloadImageForPlace(place)
        }
    }

private func downloadImageForPlace(place: Place) {
        ApplicationControls.getImageForPlace(place, withCompletion: { (image, error) -> () in
            // error checks
            dispatch_async(dispatch_get_main_queue(), {
                // UI update
                dispatch_semaphore_signal(self.semaphore)
            })
        })
    }

但是,當我點擊刷新控件時,應用程序鎖定在dispatch_semaphore_wait並且我能夠找到一種方法來重置信號量。

我會這樣使用OperationQueue

let queue = OperationQueue()
queue.maxConcurrentOperationCount = 5;

for url in imageUrls {
    queue.addOperationWithBlock { () -> Void in

        let img1 = Downloader.downloadImageWithURL(url)

        NSOperationQueue.mainQueue().addOperationWithBlock({
            //display the image or whatever
        })
    }


}

您可以以此來停止操作

queue.cancelAllOperations();

然后重新啟動整個過程。

您唯一需要更改的是,您的請求必須是同步的。 因為這種方法不適用於回調。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM