导入相应的库
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




swift3.0 从相册选取或者拍照上传图片至阿里云OSS的更多相关文章

  1. 上传图片到阿里云OSS和获取上传图片的外网url的步骤

    啥都不说  直接上代码 1.html: <form action="/bcis/api/headImgUpload.json" method="post" ...

  2. Java中使用RestFul接口上传图片到阿里云OSS服务器

    1.接口方法 import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.springfr ...

  3. vue中上传图片至阿里云oss

    1.开通阿里云的oss服务这些这里就不多做介绍了 2.登入阿里云的后台管理系统创建一个Bucket 3.在后台管理系统中进入访问控制 4.点击用户管理->新建用户->填写相关信息,就生成了 ...

  4. 上传图片到阿里云oss

    阿里云地址 登录阿里云管理控制台,创建对象存储oss private static final String endpoint = "http://oss-cn-shanghai.aliyu ...

  5. TP框架上传图片至阿里云oss

    首先安装阿里云oss扩展: composer require aliyuncs/oss-sdk-php 如果这个安装不上可以直接下载SDK的包: 链接:https://pan.baidu.com/s/ ...

  6. swoft 上传图片到 阿里云oss aliyun-oss

    1.swoft  获取上传的文件 .官方文档上面没有看到 $files = $request->getUploadedFiles(); $file = $files['file']; 2.在模型 ...

  7. laravel使用阿里云OSS上传图片

    需要自己注册阿里云账号并且开通oss服务,建立Bucket存储空间,此步骤不做演示 一.composer安装:使用composer在项目根目录执行以下命令 composer require johnl ...

  8. swift3.0调用相册

    swift3.0调用相册首先需要注意: 1.swift3.0中调用相机和相册会导致崩溃 1.需要在info.plist文件中加入两个键值对,如下: /// 都是String类型,内容任意的字符串即可 ...

  9. koa2使用阿里云oss的nodejs sdk实现上传图片

    nodejs实现上传图片到阿里云,自然是写成接口形式比较方便,前端监听input file的改变,把file对象传入到formData中传入后端,不能直接传入file对象,后端需要接受formData ...

随机推荐

  1. MyEclipse常用操作

    选择你要注释的那一行或多行代码,按Ctrl+/即可,取消注释也是选中之后按Ctrl+/即可. 如果你想使用的快捷键的注释是的话,那么你的快捷键是ctrl+shift+/我以前都是手动注释的,直接打// ...

  2. [leetcode-605-Can Place Flowers]

    Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, ...

  3. 【LeetCode】168. Excel Sheet Column Title

    题目: Given a positive integer, return its corresponding column title as appear in an Excel sheet. For ...

  4. 【Android Developers Training】 32. 向其它应用发送简单数据

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

  5. C++学习笔记——大杂烩

    C++学习笔记--大杂烩                                                         by方阳 版权声明:本文为博主原创文章,转载请指明转载地址 h ...

  6. bootstrap轮播和百叶窗

    轮播 在bootstrap里面,有设置的图片轮播的代码: <div id="carousel-example-generic" class="carousel sl ...

  7. C#调用TSC条码打印机打印条码

    #region 调用TSC打印机打印条码 /// <summary> /// 调用TSC打印机打印条码 /// </summary> /// <param name=&q ...

  8. 使用CodeDOM动态编译一个字符串表达式

    由于程序需要,计算的表达式使用字符串传输,这样对运算造成了影响.在程序中直接执行这段表达式可以得到值, 但是使用字符串就没有办法运算了, 所以想到用CodeDOM将这段字符串拼接在代码中编译 类似st ...

  9. 设置select标签的高度

    当无法给select标签设置高度的时候,给他加一个背景色,就可以设置了.

  10. PostgreSQL 使用 PreparedStatement 导致查询慢的分析

    实验环境: DB is PostgreSQL version 8.2.15 JDK1.8 测试一 使用JDBC查询一个SQL: public static void test1(String url, ...