gpt4 book ai didi

ios - Swift - NSURLSession 恢复后完成操作

转载 作者:可可西里 更新时间:2023-11-01 02:11:22 25 4
gpt4 key购买 nike

我正在尝试在 URLSession 恢复后完成一个操作。

所以我使用 url 从我的服务器下载了几张图片,一切正常。但是现在我正在尝试在完成下载后将这些图像保存到磁盘。

问题

现在我可以在下载它们的同时将它们保存在同一个查询中,但我不希望太多,因为它会使我的查询变慢。

因此,我已经通过查询向我的 func 添加了一个完成处理程序,但是当我将图像保存到该 block 中的磁盘时,它可以工作但是我无法对我的屏幕执行任何操作,因为查询尚未恢复但它被阻止了触摸我猜...

现在我希望能够在恢复查询后立即调用我的函数将图像保存到磁盘....任何人有任何想法吗?

如果有人需要更多解释或查看代码,请在下面发表评论

非常感谢任何可以提供帮助的人!

下载代码

func loadPosts(completionHandler: @escaping (Bool) -> ()) {

pageNumber = 1
appDelegate.setNetworkActivityIndicatorVisible(true)

let id = user!["id"] as! String
let url = URL(string: "http://************/Files/Posts.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let body = "id=\(id)&caption=&uuid=&page="
request.httpBody = body.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) in

DispatchQueue.global(qos: .background).async {
if error == nil {

let oldImageArray = self.cellContentArray
self.cellContentArray.removeAll(keepingCapacity: false)


do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

guard let parseJSON = json else {
print("Error while parsing")
return
}
guard let posts = parseJSON["Posts"] as? [AnyObject] else {
print("Error while parseJSONing")
return
}
for element in posts {
// here I download the stuff and it to my Array, too long and no point to show here

}

let oldImageSet = Set(oldImageArray.map({return $0.uuid}))
let newImageSet = Set(self.cellContentArray.map({return $0.uuid}))
let addedImages = newImageSet.subtracting(oldImageSet)
let addedImageSections = Array(addedImages).map{ self.cellContentArray.map({return $0.uuid}).index(of: $0)! }
let addedImageIndexSet = IndexSet(addedImageSections)
let removedImages = oldImageSet.subtracting(newImageSet)
let removedImageSections = Array(removedImages).map{ oldImageArray.map({return $0.uuid}).index(of: $0)! }
let removedImageIndexSet = IndexSet(removedImageSections)


if !addedImageIndexSet.isEmpty {
if oldImageArray.count >= 5 {
self.lastUUIDImage = oldImageArray[4].uuid
} else {

}
self.coreDataShit()
}
DispatchQueue.main.async{
print(placeholderImage.count)
if placeholderImage.count > 5 {
placeholderImage.removeFirst(placeholderImage.count - 5)
}
print("finished")
self.customView.isHidden = true
if posts.count >= 5 {
self.tableView.addInfiniteScroll { [weak self] (scrollView) -> Void in
self?.loadMore()
}}
self.activityView.stopAnimating()
self.internetView.removeFromSuperview()



self.tableView.beginUpdates()
if !addedImageIndexSet.isEmpty {
self.tableView.insertSections(addedImageIndexSet, with: .top)
}
if !removedImageIndexSet.isEmpty {
self.tableView.deleteSections(removedImageIndexSet, with: .bottom)
}
self.tableView.endUpdates()
self.tableView.finishInfiniteScroll()
self.refresher.endRefreshing()
appDelegate.setNetworkActivityIndicatorVisible(false)
completionHandler(true)

}
} catch {
DispatchQueue.main.async {
self.tableView.removeInfiniteScroll()
self.customView.isHidden = false
self.refresher.endRefreshing()
self.tableView.reloadData()
}
}


} else {
DispatchQueue.main.async(execute: {
let message = error!.localizedDescription
appDelegate.infoView(message: message, color: smoothRedColor)
})
}
}
})
task.resume()

}

保存图片

   self.loadPosts(completionHandler: { (true) in
print("completion")

let sections = self.tableView.numberOfSections
for i in 0..<sections {
self.rows += self.tableView.numberOfRows(inSection: i)
}

print(self.rows)

if self.rows <= 5 {
print("less than 5")
print(self.rows)
var i = 0

for element in self.cellContentArray {

let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let dirPath = "\(path)/images"
let url = NSURL(fileURLWithPath: dirPath)
let filePath = url.appendingPathComponent("\(element.uuid).jpg")?.path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath!) {
print("File exsists")

} else {
print("File doesn't exsist")
DispatchQueue.main.async {

let url = NSURL(string: element.fullImage!)! // convert path str to url
let imageData = NSData(contentsOf: url as URL) // get data via url and assigned imageData
let imageName = element.uuid
let saveImages = FileSaveHelper(fileName: imageName, fileExtension: .JPG, subDirectory: "images", directory: .documentDirectory)
do {
guard let image = UIImage.sd_image(with: imageData as Data!) else {
print("Error getting image")
return
}
try saveImages.saveFile(image: image)
self.saveNewImagePath(imageLink: imageName, uuid: imageName)
self.removeImage(itemName: "file\(i)", fileExtension: "jpg")
self.removeImage(itemName: self.lastUUIDImage, fileExtension: "jpg")

i += 1

} catch {
print(error)
}
}
}

}
}

})

tableView 单元格中的图像

 self.postImage.sd_setImage(with: URL(string: content.fullImage!), placeholderImage: placeHolder, options: .retryFailed) { (image:UIImage?, error:Error?, cached:SDImageCacheType, url:URL?) in

}

最佳答案

在您保存图像的代码中,这行代码阻塞了您的 UI

let imageData = NSData(contentsOf: url as URL) // get data via url and assigned imageData

这不是从服务器下载图片的正确方法,您应该使用 URLSession 异步下载图片

关于ios - Swift - NSURLSession 恢复后完成操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40821431/

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