项目中导入SwiftyJSON和Alamofire
pod ‘SwiftyJSON’, ‘4.0.0’ pod ‘Alamofire’, ‘4.9.0’
选择图片,获取上传路径列表
import UIKit
class UserInfoController: UIViewController {
private func selectHeadImage() {
let imagePickerVC = TZImagePickerController(maxImagesCount: 1, delegate: self)
imagePickerVC?.modalTransitionStyle = .flipHorizontal
imagePickerVC?.modalPresentationStyle = .overCurrentContext
imagePickerVC?.showSelectBtn = false
imagePickerVC?.allowCrop = true
imagePickerVC?.cropRect = CGRect(x: 0, y: (UIScreen.main.bounds.size.height - UIScreen.main.bounds.size.width)/2.0, w: UIScreen.main.bounds.size.width, h: UIScreen.main.bounds.size.width)
imagePickerVC?.allowPickingVideo = false
imagePickerVC?.allowPickingOriginalPhoto = false
imagePickerVC?.didFinishPickingPhotosHandle = { [weak self] photo, assets, isSelectOriginalPhoto in
guard let photo = photo, let this = self,photo.count != 0 else {return}
let img = photo.first
this.getUploadUrl([img])
}
self.presentVC(imagePickerVC!)
}
private func getUploadURL(_ imageArr: [UIImage]) {
var typeArr: [String] = []
for img in imageArr {
if let data = img.jpegData(compressionQuality: 1) {
let type = data.getImageFormat()
if type == .JPEG {
typeArr.append("image/jpeg")
} else if type == .PNG {
typeArr.append("image/png")
}
}
}
AlertHUD.show()
var params: [String : Any] = [:]
params["contentType"] = typeArr
JRNetworkManager.shared.request(CommonAPI.uploadUrl(params), completed: { [weak self] (result) in
AlertHUD.dismiss(withDelay: 0.1)
guard let this = self else { return }
if let pathArr = result.object as? [String] {
this.imagesUpload(imageArr: imageArr, pathArr: pathArr, contentTypeArr: typeArr)
}
}, failed: { (status, error) in
AlertHUD.showText(error)
})
}
private func imagesUpload(imageArr: [UIImage], pathArr: [String], contentTypeArr: [String]) {
if imageArr.count == pathArr.count || imageArr.count == contentTypeArr.count {
for (index, img) in imageArr.enumerated() {
let path = pathArr[index]
JRNetworkManager.shared.aliyunUploadImage(img, path, completed: { [weak self] (result) in
if let photoPath = path.components(separatedBy: "?").first {
self?.editAvatar(path: photoPath)
}
}, failed: { (status, error)in
AlertHUD.showMsg("操作失败")
})
}
}
}
private func editAvatar(path: String) {
}
}
Alamofire使用put方式上传图片到阿里云
import Foundation
import Alamofire
import SwiftyJSON
enum NetworkStatus : String {
case success = "00000"
case networkError = "A0001"
case otherError = "-1"
}
class JRNetworkManager: NSObject {
static let shared = JRNetworkManager()
typealias CompletedBlock = ((JSON) -> Void)
typealias FailedBlock = ((NetworkStatus, String) -> Void)
private override init() {
super.init()
}
func aliyunUploadImage(_ image: UIImage, _ url: String, completed: @escaping CompletedBlock, failed: @escaping FailedBlock) {
if let imageData = image.jpegData(compressionQuality: 0.5) {
let reURL = url
let stream = InputStream(data: imageData)
var uploadHeaders: HTTPHeaders = [:]
uploadHeaders["Content-Type"] = "image/jpeg"
do {
let newurl = try reURL.asURL()
upload(stream, to: newurl , method: .put,headers: uploadHeaders)
let tempData = JSON(["url":url])
completed(tempData)
} catch {
failed(.otherError, "上传失败")
}
} else {
failed(.otherError, "上传失败")
}
}
}
根据Data获取文件的contentType
import Foundation
enum ImageFormat {
case Unknow
case JPEG
case PNG
case GIF
case TIFF
case WebP
case HEIC
case HEIF
}
extension Data {
func getImageFormat() -> ImageFormat {
var buffer = [UInt8](repeating: 0, count: 1)
self.copyBytes(to: &buffer, count: 1)
switch buffer {
case [0xFF]: return .JPEG
case [0x89]: return .PNG
case [0x47]: return .GIF
case [0x49],[0x4D]: return .TIFF
case [0x52] where self.count >= 12:
if let str = String(data: self[0...11], encoding: .ascii), str.hasPrefix("RIFF"), str.hasSuffix("WEBP") {
return .WebP
}
case [0x00] where self.count >= 12:
if let str = String(data: self[8...11], encoding: .ascii) {
let HEICBitMaps = Set(["heic", "heis", "heix", "hevc", "hevx"])
if HEICBitMaps.contains(str) {
return .HEIC
}
let HEIFBitMaps = Set(["mif1", "msf1"])
if HEIFBitMaps.contains(str) {
return .HEIF
}
}
default: break;
}
return .Unknow
}
}
|