gpt4 book ai didi

iOS - 并发执行 5 个操作,使用 NSOperationQueue 将图像上传到服务器,然后在 Objective-c 中执行单个任务

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:31:18 25 4
gpt4 key购买 nike

我必须同时使用 nsoperationqueue 执行以下操作。

我需要在后台同时执行多个操作,例如 5(上传 文件到服务器),我必须根据后续场景管理所有队列

  • 1) 2G网络只执行1个操作,其余4个操作应该停止

  • 2) 网络是 3G/Wifi 并行执行所有操作。

我如何使用 Objective-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
})
}

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

关于iOS - 并发执行 5 个操作,使用 NSOperationQueue 将图像上传到服务器,然后在 Objective-c 中执行单个任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44194204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com