• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

swift3.0从相册选取或者拍照上传图片至阿里云OSS

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
导入相应的库
import Photos
import AliyunOSSiOS

选取照片需要继承 UIImagePickerControllerDelegate,UINavigationControllerDelegate

class TestViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    
}

在info.plist中添加相关配置如下

<!-- 相册 -->   
<key>NSPhotoLibraryUsageDescription</key>   
<string>App需要您的同意,才能访问相册</string>   
<!-- 相机 -->   
<key>NSCameraUsageDescription</key>   
<string>App需要您的同意,才能访问相机</string>  

从相册选择图片

 func selectPicture() {
        
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            let picker = UIImagePickerController()
            picker.delegate = self
            picker.sourceType = UIImagePickerControllerSourceType.photoLibrary
            self.present(picker, animated: true, completion: {
                () -> Void in
            })
        }else{
            print("error")
        }
   }

拍照图片选取

func camera() {
        
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            let picker = UIImagePickerController()
            picker.delegate = self
            picker.sourceType = UIImagePickerControllerSourceType.camera
            self.present(picker, animated: true, completion: { () -> Void in
            })
        }else{
            print("error")
        }
        
    }

拍照与相册选取会进入同一个回调中,如下所示

func imagePickerController(_ picker:UIImagePickerController, didFinishPickingMediaWithInfo info: [String :Any]){
        
        let pickedImage = info[UIImagePickerControllerOriginalImage] as! UIImage,
            type:String = (info[UIImagePickerControllerMediaType]as!String)
        
        let fileManager = FileManager.default
        let rootPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,
                                                           .userDomainMask, true)[0] as String
        
        let date = NSDate(),
            timeInterval = date.timeIntervalSince1970 * 1000

        //将图片保存在本地
        let filePath = "\(rootPath)/" + String(timeInterval) + ".png"
        let imageData = UIImageJPEGRepresentation(pickedImage, 1.0)
        fileManager.createFile(atPath: filePath, contents: imageData, attributes: nil)
        
        //上传
        uploadPic(url: URL.init(fileURLWithPath: filePath))
        
        if type == "public.image" {
            //关闭选择框
            picker.dismiss(animated:true, completion:nil)
        }
        
    }

  

初始化上传配置相关信息(通过StsToken回调管理token信息) 我是通过Alamofire获取数据

//初始化上传设置
    func initClient() {
        
        //上传配置设置
        let conf = OSSClientConfiguration()
        conf.maxRetryCount = 2
        conf.timeoutIntervalForRequest = 300
        conf.timeoutIntervalForResource = TimeInterval(24 * 60 * 60)
        conf.maxConcurrentRequestCount = 50
        
        //实现获取StsToken回调
        let credential2:OSSCredentialProvider = OSSFederationCredentialProvider.init(federationTokenGetter: { () -> OSSFederationToken? in
            
            let tcs = OSSTaskCompletionSource<AnyObject>.init()
            
            Alamofire.request("获取相关配置的接口地址", method: .get, parameters: [: ])
                .responseJSON { (response) in
                    
                    if let value = response.result.value {
                        
                        let json = JSON(value)
                        
                        if json["code"] == 1{
                            tcs.setResult(json as AnyObject?)
                        }else{
                            tcs.setError("error" as! Error)
                        }
                    }
            }
            
            tcs.task.waitUntilFinished()
            
            if tcs.task.error != nil {
                return nil
            }else {
                
                let jsonData:JSON = JSON(tcs.task.result as AnyObject),
                tokenInfo:OSSFederationToken = OSSFederationToken()
                
                tokenInfo.tAccessKey = "通过返回的jsonData自行赋值"
                tokenInfo.tSecretKey = "通过返回的jsonData自行赋值"
                tokenInfo.tToken = "通过返回的jsonData自行赋值"
                tokenInfo.expirationTimeInGMTFormat = "通过返回的jsonData自行赋值"
                
                return tokenInfo
            }
            
        })
        
        //实例化
        ossClient = OSSClient(endpoint: EndPoint, credentialProvider: credential2, clientConfiguration: conf)        
    }

上传方法为(在上传之前先调用initClient):

    //上传图片
    func uploadPic(url: URL) {
        
        let ossPutObj: OSSPutObjectRequest = OSSPutObjectRequest()
        //key为上传到阿里云的路径
        let  key = "image/" + md5String(str: String(describing: url)) + ".jpg"
        
        ossPutObj.bucketName = BucketName
        ossPutObj.objectKey = key
        ossPutObj.uploadingFileURL = url
        
        ossPutObj.uploadProgress = { (bytesSent, totalBytesSent, totalBytesExpectedToSend) -> Void in
            print(String(bytesSent) + "/" + String(totalBytesSent) + "/" + String(totalBytesExpectedToSend))
        }
        
        let uploadTask = ossClient?.putObject(ossPutObj)
        
        uploadTask?.continue({ (uploadTask) -> Any? in
            
            if let _err = uploadTask.error {
                print(_err)
            } else {
                if (uploadTask.result as? OSSPutObjectResult) != nil {
                     //上传成功后预览地址自行拼接     
                }
            }
            return uploadTask
        })
        
    }

  

"https://oss-cn-hangzhou.aliyuncs.com"

 

 

  

, UINavigationControllerDelegate


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap