swift 拍照(相册选择)并将图片上传至阿里云

先在 info.plist 文件中配置相机,相册权限:

建议直接复制英文部分

Privacy - Camera Usage Description 开启相机权限,以便您拍照上传照片

Privacy - Photo Library Usage Description 开启相册权限,以便您上传照片

image.png

代码部分也可以直接复制粘贴使用;这样就得到了选择的图片文件;

、、、

//底部弹框选择
func showBottomAlert(){
    
    let alertController=UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
    
    let cancel=UIAlertAction(title:"取消", style: .cancel, handler: nil)
    let takingPictures=UIAlertAction(title:"拍照", style: .default)
    {
        action in
        self.goCamera()
        
    }
    let localPhoto=UIAlertAction(title:"相册", style: .default)
    {
        action in
        self.goImage()
        
    }
    alertController.addAction(cancel)
    alertController.addAction(takingPictures)
    alertController.addAction(localPhoto)
    self.present(alertController, animated:true, completion:nil)
}

/// 去拍照
func goCamera(){
    if UIImagePickerController.isSourceTypeAvailable(.camera){
        let  cameraPicker = UIImagePickerController()
        cameraPicker.delegate = self
        cameraPicker.allowsEditing = true
        cameraPicker.sourceType = .camera
        //在需要的地方present出来
        self.present(cameraPicker, animated: true, completion: nil)
    } else {
        print("不支持拍照")
    }
}

/// 去相册
func goImage(){
    let photoPicker =  UIImagePickerController()
    photoPicker.delegate = self
    photoPicker.allowsEditing = true
    photoPicker.sourceType = .photoLibrary
    //在需要的地方present出来
    self.present(photoPicker, animated: true, completion: nil)
}
 //图片代理回调
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    VVLoadView.show()
    print("获得照片============= \(info)")
    let image : UIImage = info[UIImagePickerController.InfoKey.editedImage] as! UIImage
    
    //显示设置的照片
    self.takePhotoBtn.setTitle("", for: .normal)
    self.takePhotoBtn.setBackgroundImage(image, for: .normal)
    
//        let rootPath:NSString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
//        //图片文件路径
//        let filePath = rootPath.strings(byAppendingPaths: ["selectedImage.jpg"]).first
    let pickedImage = image.normalizedImage()
    let originData = pickedImage.jpegData(compressionQuality: 1.0)
    var imageData:Data?
    if ((originData?.count ?? 0) / 1024) > 5000 {
        imageData = pickedImage.jpegData(compressionQuality: 0.1)
    } else {
        imageData = pickedImage.jpegData(compressionQuality: 0.3)
    }
    
  //阿里工具类图片上传
    DSImageUploader.shared.uploadImages(imageData!) {(urlStr, success) in
        DispatchQueue.main.async {
            VVLoadView.shareInstance.dissMissAnim()
        }
        if success {
            self.enterPhoto = urlStr
//这是最终获得的图片url,可以随意使用
            print("上传成功:",urlStr)
        } else {
            VVHub.show(msg: "上传失败")
        }
    }
    
    self.dismiss(animated: true, completion: nil)
}

、、、

接下来就是配置阿里云上传了

  1. pods导入阿里库

pod 'AliyunOSSiOS'

2.封装一个公共上传的工具类

、、、

   import Foundation
    import AliyunOSSiOS

typealias StringBoolCallback = (_ text:String, _ value:Bool) -> Void

class DSImageUploader {

static let shared = DSImageUploader.init()

let config = OSSClientConfiguration()

let credantial = OSSFederationCredentialProvider { () -> OSSFederationToken? in

    lettoken =OSSFederationToken()

    token.tAccessKey=DSPublicKeys.OSS_KEY

    token.tSecretKey = DSPublicKeys.OSS_SECRECT

    returntoken

}

let client: OSSClient

init() {

    OSSLog.enable()

    config.maxRetryCount = 2

    config.timeoutIntervalForRequest = 30

    config.timeoutIntervalForResource = 120

    client=OSSClient(endpoint:DSPublicKeys.OSS_END_POINT, credentialProvider:credantial, clientConfiguration:config)

  }
}

extension DSImageUploader {

  funcuploadImages(_image:Data, completionHandler:@escaping StringBoolCallback) {

    letinterval =Date().timeIntervalSince1970

    let put = OSSPutObjectRequest()

    put.bucketName = "dasyun-public-statics"

    put.objectKey="IOSYunPark\(interval).jpg"

    put.uploadingData= image

    put.uploadProgress= { bytesSent, totalByteSent, totalByteExpectedToSendin

//            print(bytesSent, totalByteSent, totalByteExpectedToSend)

    }

    letputTask =client.putObject(put)

    putTask.continue({ (task:OSSTask) ->Any?in

        iftask.error==nil{

            print("upload object success!")

            letstr =DSPublicKeys.OSS_END_POINT.components(separatedBy:CharacterSet.init(charactersIn:"//")).last

            leturl =String(format:"http://%@.%@/%@", put.bucketName, str!, put.objectKey)

            print("上传图片成功:", url)

            DispatchQueue.main.async{

               completionHandler(url, true)

            }

        }else{

            leterror:NSError= (task.error)!asNSError

            print("图片上传错误:",error.description)

            completionHandler("", false)

        }

        returnnil

        }).waitUntilFinished()

  }

}

、、、

用的时候就调用:

imageData 为拍照或相册选择后的图片转为 Data :

let imageData = image.jpegData(compressionQuality: 1.0)

、、、

DSImageUploader.shared.uploadImages(imageData!) { [weakself] (urlStr, success)in

        guard self != nil else { return }

        ifsuccess {

        //"上传成功"

        }else{

           //"上传失败"

        }

    }

、、、

复制上门代码需要注意的是 bucketName 参数是需要看自己在 阿里上配置的,不是固定死的;objectKey 参数随意命名;

DSPublicKeys.OSS_KEY(图2) 是我自己定义的宏,用自己的阿里 key 和 secrect 字符串替换即可,DSPublicKeys.OSS_END_POINT 同样;这四个参数都是配置完阿里后都会有的;

image
image

你可能感兴趣的:(swift 拍照(相册选择)并将图片上传至阿里云)