簡體   English   中英

iOS - 並發執行5次操作,使用NSOperationQueue將圖像上傳到服務器,然后在Objective-c中使用單個任務

[英]iOS - Concurrency performing 5 operations uploading images to server using NSOperationQueue followed by single Task in Objective-c

我必須同時使用nsoperationqueue執行以下操作。

我需要在后台執行多個操作,例如5(將文件上傳到服務器),我必須管理所有隊列取決於跟隨scenorio

  • 1)網絡是2G只執行1次操作,其余4次操作應該停止

  • 2)網絡是3G / Wifi並行執行所有操作。

我怎樣才能實現這個目標-c ???

提前致謝。

檢查您的互聯網狀態並根據需要處理操作

串行調度隊列

在串行隊列中,每個任務在執行之前等待上一個任務完成。

當網絡速度很慢時,您可以使用它。

let serialQueue = dispatch_queue_create("com.imagesQueue", DISPATCH_QUEUE_SERIAL) 

dispatch_async(serialQueue) { () -> Void in
    let img1 = Downloader .downloadImageWithURL(imageURLs[0])
    dispatch_async(dispatch_get_main_queue(), {
        self.imageView1.image = img1
   })      
}

dispatch_async(serialQueue) { () -> Void in
   let img2 = Downloader.downloadImageWithURL(imageURLs[1])
   dispatch_async(dispatch_get_main_queue(), {
       self.imageView2.image = img2
   })
}

並發隊列

每個下載器都被視為一項任務,所有任務都在同一時間執行。

當網絡快速使用它。

let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue) { () -> Void in

        let img1 = Downloader.downloadImageWithURL(imageURLs[0])
        dispatch_async(dispatch_get_main_queue(), {

            self.imageView1.image = img1
        })

}

dispatch_async(queue) { () -> Void in

        let img2 = Downloader.downloadImageWithURL(imageURLs[1])

        dispatch_async(dispatch_get_main_queue(), {

            self.imageView2.image = img2
        })

}

NSOpration

當您需要啟動依賴於另一個的執行的操作時,您將需要使用NSOperation。

您還可以設置操作優先級。

addDependency用於不同的operation

queue = OperationQueue()

let operation1 = BlockOperation(block: {
     let img1 = Downloader.downloadImageWithURL(url: imageURLs[0])
     OperationQueue.main.addOperation({
          self.imgView1.image = img1
     })
})

// completionBlock for operation        
operation1.completionBlock = {
    print("Operation 1 completed")
}

// Add Operation into queue
queue.addOperation(operation1)

let operation2 = BlockOperation(block: {
     let img2 = Downloader.downloadImageWithURL(url: imageURLs[1])
     OperationQueue.main.addOperation({
          self.imgView2.image = img2
     })
})

// Operation 2 are depend on operation 1. when operation 1 completed after operation 2 is execute. 
operation2.addDependency(operation1)

queue.addOperation(operation2)

您還可以設置優先級

public enum NSOperationQueuePriority : Int {
    case VeryLow
    case Low
    case Normal
    case High
    case VeryHigh
}

您還可以設置並發操作

queue = OperationQueue()

queue.addOperation { () -> Void in

    let img1 = Downloader.downloadImageWithURL(url: imageURLs[0])

    OperationQueue.main.addOperation({
        self.imgView1.image = img1
    })
 }

您也可以取消並完成操作。

暫無
暫無

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

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