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

时间:2024-06-08 13:08:08
导入相应的库
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