letkTimeoutInterval =10.0
///成功返回数据Block
typealiasreceiveDataCompletionBlock=(responseDict:NSDictionary)->Void
///返回数据失败Block
typealiasfaildDataCompletionBlock=(failString:NSString)->Void
///上传图片进度
typealiasuploadProgressBlock = (percent:Double,totalBytesWritten:Double,totalBytesExpectedToWrite:Double) ->Void
/**
上传图片
- parameter dict:参数
- parameter urlStr:url地址
- parameter images:需要上传的图片
- parameter successResponseDataBlock:成功返回
- parameter faildResponseDataBlock:失败
- parameter uploadProgressDataBlock:进度
*/
funcpostUploadsWithUrl(dict:NSDictionary,urlStr:String,images:[UIImage],successResponseDataBlock:receiveDataCompletionBlock,faildResponseDataBlock:faildDataCompletionBlock,uploadProgressDataBlock:uploadProgressBlock){
ifimages.count==0{
return
}
letmanager =AFHTTPRequestOperationManager()
manager.responseSerializer=AFHTTPResponseSerializer()
lettype ="application/json"
letsets=NSSet()
manager.responseSerializer.acceptableContentTypes=sets.setByAddingObject(type)
manager.requestSerializer.setValue(kPackage, forHTTPHeaderField:"package")
manager.requestSerializer.timeoutInterval=kTimeoutInterval
letaccess_token =XDUserDefaults.getStringForKey(kKeyAccessToken)!asString
manager.requestSerializer.setValue("Bearer\(access_token)", forHTTPHeaderField:"Authorization")
letoperation = manager.POST(urlStr, parameters: dict, constructingBodyWithBlock: { (data:AFMultipartFormData) ->Voidin
//data.appendPartWithFileData(UIImagePNGRepresentation(UIImage(named: "tiger")!)!, name: "gushi", fileName:"tiger.jpg", mimeType: "image/png/jpg/jpeg")
vari =0
//根据当前系统时间生成图片名称
letdate =NSDate()
letformatter =NSDateFormatter()
formatter.dateFormat="YYYYMMddHHmmss"
letdateString = formatter.stringFromDate(date)
forimageinimages {
varfileName ="\(dateString)-\(i)"
//type of image
vardataOfImage:NSData
if(UIImagePNGRepresentation(image) !=nil){
dataOfImage = (UIImagePNGRepresentation(image))!
fileName +=".png"
}else{
dataOfImage =UIImageJPEGRepresentation(image,1)!
fileName +=".jpg"
}
data.appendPartWithFileData(dataOfImage, name:"photo\(i)"+fileName, fileName:fileName, mimeType:"image/png/jpg/jpeg")
i++
}
}, success: { (operation:AFHTTPRequestOperation, response:AnyObject) ->Voidin
//successResponseDataBlock(responseDict: response as! NSDictionary)
successResponseDataBlock(responseDict: ["data":"success"])
}) { (operation:AFHTTPRequestOperation?, err:NSError) ->Voidin
faildResponseDataBlock(failString: err.description)
}
operation?.setUploadProgressBlock({ (bytesWritten:UInt, totalBytesWritten:Int64, totalBytesExpectedToWritten:Int64) ->Voidin
letpercent =Double(totalBytesWritten) /Double(totalBytesExpectedToWritten)
//print("-----------------------\(totalBytesWritten)/\(totalBytesExpectedToWritten) = \(percent)")
uploadProgressDataBlock(percent: percent, totalBytesWritten:Double(totalBytesWritten), totalBytesExpectedToWrite:Double(totalBytesExpectedToWritten))
})
}