繁体   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