加入当后台的接口,只支持上传一张图片的时候,如何实现上传多张图片?
在网上基本看到了两种解决问题的方案,一种是使用递归的方式,另外一种是使用dispatch_group的方式。我在项目中最终使用了这种递归的方式。
//解决压缩图片,然后使用Dispatch_group后,上传图片,有一张图片重复的问题
func uploadMutiPatientImage(images:[UIImage],currentIndex:NSInteger) {
if images.count > 0 {
//压缩图片
UIImage.lca_compressedImageFiles(images[currentIndex], imageBytes: 500, block: { (image) in
NetworkTools.sharedTools.uploadPhoto("接口地址", parameters: nil, headers: ["AccessToken":MAHttpClient.Router.OAuthToken!], imageArray: [image], name: "upfile", currentProgress: { (progress) in
}, success: { [weak self] (result) in
if let strongSelf = self {
if let result = result {
let status = result["status"] as! Int
//图片上传成功
if status == 0 {
if let url = result["url"] as? String {
//TODO:处理相关业务逻辑
//如果图片没有上传完成,继续上传
if currentIndex < images.count - 1 {
let nextIndex = currentIndex + 1
//递归调用自己
strongSelf.uploadMutiPatientImage(images, currentIndex: nextIndex)
}
}
}else {
strongSelf.failImages.append(image)
}
}
}, failure: { (errorCode) in
self.failImages.append(image)
})
})
}else {
}
}
我通过下面这种写法的时候,竟然出现了上传多张图片的时候,有一张图片重复的问题。
最终发现,如果把中间的压缩代码去掉,上传的时候就不会出现任何问题。
func uploadMutiPatientImage(images:[UIImage]){
var result = [UIImage]()
for image in images {
result.append(image)
}
var failImages = [UIImage]()
let group = dispatch_group_create()
let lock = NSLock()
isAllUpload = false
var count = 0
ProgressHUD.lca_showProgress(Float(count)/Float(images.count))
for i in 0 ..< images.count {
dispatch_group_enter(group)
UIImage.lca_compressedImageFiles(images[i], imageBytes: 300, block: { (image) in
NetworkTools.sharedTools.uploadPhoto("上传地址", parameters: nil, headers: ["AccessToken":MAHttpClient.Router.OAuthToken!], imageArray: [images[i]], name: "upfile", currentProgress: { (progress) in
}, success: { [weak self] (result) in
if let strongSelf = self {
if let result = result {
let status = result["status"] as! Int
if status == 0 {
print("第\(i)张上传成功")
dispatch_group_leave(group)
if let url = result["url"] as? String {
//TODO:处理成功的业务
}else {
print("第\(i)张上传失败")
}
}
}
}, failure: { (errorCode) in
dispatch_group_leave(group)
print("第\(i)张上传失败")
})
})
}
dispatch_group_notify(group, dispatch_get_main_queue()) {
}
}
网友评论