美文网首页Swift学习
swift 阿里云文件上传

swift 阿里云文件上传

作者: 松龄学编程 | 来源:发表于2020-06-06 09:27 被阅读0次
    import AliyunOSSiOS
    
    class Uploader {
        
        static let shared = Uploader()
        
        let config = OSSClientConfiguration()
        
        let credantial = OSSFederationCredentialProvider { () -> OSSFederationToken? in
            let token = OSSFederationToken()
            token.tAccessKey = AccessKey
            token.tSecretKey = SecretKey
            return token
        }
        
        let client: OSSClient
        
        init() {
            OSSLog.enable()
            
            config.maxRetryCount = 2
            config.timeoutIntervalForRequest = 30
            config.timeoutIntervalForResource = 30
            config.maxConcurrentRequestCount = 10
            
            client = OSSClient(endpoint: endPoint,
                               credentialProvider: credantial,
                               clientConfiguration: config)
        }
    }
    
    extension Uploader {
        func uploadImages(_ images: [ImageFile], completionHandler: @escaping (() -> Void)) {
            var count = images.count
            
            for image in images {
                DispatchQueue.global().async {
                    self.uploadImage(image) {
                        count -= 1
                        if count == 0 {
                            completionHandler()
                        }
                    }
                }
            }
        }
        
        private func uploadImage(_ image: ImageFile, completionHandler: @escaping (() -> Void)) {
            let put = OSSPutObjectRequest()
            put.contentType = "image/jpeg"
            put.bucketName = image_BucketName
            put.objectKey = image.name
            put.uploadingData = image.data ?? Data()
            put.uploadProgress = { bytesSent, totalByteSent, totalByteExpectedToSend in
                print(bytesSent, totalByteSent, totalByteExpectedToSend)
            }
            
            let putTask = client.putObject(put)
            putTask.continue({ (task: OSSTask<AnyObject>) -> Any? in
                if task.error == nil {
                    print("upload object success!")
                    DispatchQueue.main.async {
                        completionHandler()
                    }
                } else {
                    print("upload object failed, error: \(task.error?.localizedDescription ?? "")")
                }
                return nil
            })
        }
    }
    
    struct ImageFile {
        let image: UIImage
        let name: String
        let data: Data?
        
        let maxSize: CGFloat
        
        var urlString: String {
            return image_EndPoint + "/" + name
        }
        
        init(image: UIImage, maxSize: CGFloat = 0) {
            self.image = image
            self.maxSize = maxSize
            let name = "user/" + getUUID() + ".jpg"
            self.name = name
            var quality: CGFloat = 1
            var data = image.jpegData(compressionQuality: quality)
            var sizeOriginKB: CGFloat = CGFloat((data?.count ?? 0)) / 1024.0
            if maxSize > 0 {
                while sizeOriginKB > maxSize && quality > 0 {
                    quality -= 0.1
                    data = image.jpegData(compressionQuality: quality)
                    sizeOriginKB = CGFloat((data?.count) ?? 0) / 1024.0
                }
            }
            
            self.data = data
            print("sizeOriginKB: \(sizeOriginKB)")
            print("uuid: \(self.name)")
        }
    }
    
    func getUUID() -> String {
        let uuidRef = CFUUIDCreate(nil)
        let uuidStringRef = CFUUIDCreateString(nil,uuidRef)
        return uuidStringRef! as String
    }
    

    使用的地方

    let imageFiles = viewModel.images.map { (image) -> ImageFile in
                return ImageFile(image: image)
            }
            Uploader.shared.uploadImages(imageFiles) { [weak self] in
                guard let `self` = self else { return }
                let photosUrl = imageFiles.map { $0.urlString }.joined(separator: ",")
                self.contents.result["photosUrl"] = photosUrl
                print("imageFile: \(photosUrl)")
                self.submit()
            }
    

    相关文章

      网友评论

        本文标题:swift 阿里云文件上传

        本文链接:https://www.haomeiwen.com/subject/dplgzhtx.html