Swift - 使用URLSession加载数据、下载、上传文件

Swift - 使用URLSession加载数据、下载、上传文件,第1张

概述URLSession 类支持三种类型的任务:加载数据、下载和上传。下面通过样例分别进行介绍。(本文代码已升级至  Swift3) 1,使用Data Task加载数据 使用全局的  URLSession.shared 和  dataTask 方法创建。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 func  sessionLoadDat URLSession类支持三种类型的任务:加载数据、下载和上传。下面通过样例分别进行介绍。(本文代码已升级至 Swift3
1,使用Data Task加载数据 使用全局的 URLSession.shareddataTask方法创建。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 func@H_502_79@ sessionLoadData(){@H_502_79@ @H_502_79@ //创建URL对象@H_502_79@ @H_502_79@ let@H_502_79@ urlString =@H_502_79@ "http://hangge.com"@H_502_79@ url =@H_502_79@ URL@H_502_79@ (string:urlString)@H_502_79@ //创建请求对象@H_502_79@ request =@H_502_79@ URLRequest@H_502_79@ (url: url!)@H_502_79@ @H_502_79@ session =@H_502_79@ URLSession@H_502_79@ .shared@H_502_79@ dataTask = session.dataTask(with: request,@H_502_79@ @H_502_79@ completionHandler: {(data,response,error) ->@H_502_79@ VoID@H_502_79@ in@H_502_79@ if@H_502_79@ error !=@H_502_79@ nil@H_502_79@ {@H_502_79@ @H_502_79@ print@H_502_79@ (error.deBUGDescription)@H_502_79@ }@H_502_79@ else@H_502_79@ {@H_502_79@ str =@H_502_79@ String@H_502_79@ (data: data!,enCoding:@H_502_79@ String@H_502_79@ .@H_502_79@ EnCoding@H_502_79@ .utf8)@H_502_79@ (str)@H_502_79@ }@H_502_79@ })@H_502_79@ as@H_502_79@ URLSessionTask@H_502_79@ @H_502_79@ //使用resume方法启动任务@H_502_79@ dataTask.resume()@H_502_79@ }@H_502_79@
运行结果如下:
2,使用Download Task来下载文件 (1)不需要获取进度 使用全局的 URLSession.shareddownloadTask方法即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 func@H_502_79@ sessionSimpleDownload(){@H_502_79@ @H_502_79@ //下载地址@H_502_79@ @H_502_79@ let@H_502_79@ url =@H_502_79@ URL@H_502_79@ (string:@H_502_79@ "http://hangge.com/blog/images/logo.png"@H_502_79@ )@H_502_79@ //请求@H_502_79@ request =@H_502_79@ URLRequest@H_502_79@ (url: url!)@H_502_79@ @H_502_79@ session =@H_502_79@ URLSession@H_502_79@ .shared@H_502_79@ //下载任务@H_502_79@ downloadTask = session.downloadTask(with: request,@H_502_79@ @H_502_79@ completionHandler: { (location:@H_502_79@ ?,response:@H_502_79@ URLResponse@H_502_79@ Error@H_502_79@ ?)@H_502_79@ ->@H_502_79@ VoID@H_502_79@ in@H_502_79@ //输出下载文件原来的存放目录@H_502_79@ @H_502_79@ print@H_502_79@ (@H_502_79@ "location:\(location)"@H_502_79@ )@H_502_79@ //location位置转换@H_502_79@ locationPath = location!.path@H_502_79@ //拷贝到用户目录@H_502_79@ documnets:@H_502_79@ String@H_502_79@ =@H_502_79@ NSHomeDirectory@H_502_79@ () +@H_502_79@ "/documents/1.png"@H_502_79@ //创建文件管理器@H_502_79@ @H_536_404@fileManager =@H_502_79@ fileManager@H_502_79@ .@H_502_79@ default@H_502_79@ try! fileManager.moveItem(atPath: locationPath,topath: documnets)@H_502_79@ "new location:\(documnets)"@H_502_79@ )@H_502_79@ })@H_502_79@ @H_502_79@ //使用resume方法启动任务@H_502_79@ downloadTask.resume()@H_502_79@ }@H_502_79@
运行结果如下:

(2)实时获取进度
需要使用自定义的 URLSession对象和 downloadTask方法 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 @H_966_502@ 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
import@H_502_79@ UIKit@H_502_79@ class@H_502_79@ VIEwController@H_502_79@ :@H_502_79@ UIVIEwController@H_502_79@ ,@H_502_79@ URLSessionDownloadDelegate@H_502_79@ {@H_502_79@ @H_502_79@ private@H_502_79@ lazy@H_502_79@ var@H_502_79@ session:@H_502_79@ = {@H_502_79@ //只执行一次@H_502_79@ config =@H_502_79@ URLSessionConfiguration@H_502_79@ .@H_502_79@ default@H_502_79@ currentSession =@H_502_79@ (configuration: config,delegate:@H_502_79@ self@H_502_79@ )@H_502_79@ return@H_502_79@ currentSession@H_502_79@ }()@H_502_79@ @H_502_79@ overrIDe@H_502_79@ vIEwDIDLoad() {@H_502_79@ super@H_502_79@ .vIEwDIDLoad()@H_502_79@ @H_502_79@ sessionSeniorDownload()@H_502_79@ }@H_502_79@ @H_536_404@@H_502_79@ //下载文件@H_502_79@ sessionSeniorDownload(){@H_502_79@ //下载地址@H_502_79@ (string:@H_502_79@ "http://hangge.com/blog/images/logo.png"@H_502_79@ )@H_502_79@ //请求@H_502_79@ (url: url!)@H_502_79@ @H_502_79@ //下载任务@H_502_79@ downloadTask = session.downloadTask(with: request)@H_502_79@ @H_502_79@ //使用resume方法启动任务@H_502_79@ downloadTask.resume()@H_502_79@ }@H_502_79@ @H_502_79@ //下载代理方法,下载结束@H_502_79@ urlSession(_ session:@H_502_79@ URLSessionDownloadTask@H_502_79@ ) {@H_502_79@ //下载结束@H_502_79@ (@H_502_79@ "下载结束"@H_502_79@ )@H_502_79@ @H_502_79@ //输出下载文件原来的存放目录@H_502_79@ "location:\(location)"@H_502_79@ )@H_502_79@ //location位置转换@H_502_79@ locationPath = location.path@H_502_79@ //拷贝到用户目录@H_502_79@ documnets:@H_502_79@ =@H_502_79@ NSHomeDirectory@H_502_79@ () +@H_502_79@ "/documents/2.png"@H_502_79@ //创建文件管理器@H_502_79@ fileManager =@H_502_79@ fileManager@H_502_79@ default@H_502_79@ "new location:\(documnets)"@H_502_79@ )@H_502_79@ }@H_502_79@ @H_502_79@ //下载代理方法,监听下载进度@H_502_79@ dIDWriteData bytesWritten:@H_502_79@ Int64@H_502_79@ ) {@H_502_79@ //获取进度@H_502_79@ written:@H_502_79@ CGfloat@H_502_79@ = (@H_502_79@ )(totalBytesWritten)@H_502_79@ total:@H_502_79@ = (@H_502_79@ CGfloat@H_502_79@ )(totalBytesExpectedToWrite)@H_502_79@ pro:@H_502_79@ = written/total@H_502_79@ "下载进度:\(pro)"@H_502_79@ )@H_502_79@ }@H_502_79@ @H_502_79@ //下载代理方法,下载偏移@H_502_79@ dIDResumeatOffset fileOffset:@H_502_79@ Int64@H_502_79@ ) {@H_502_79@ //下载偏移,主要用于暂停续传@H_502_79@ }@H_502_79@ @H_502_79@ dIDReceiveMemoryWarning() {@H_502_79@ .dIDReceiveMemoryWarning()@H_502_79@ }@H_502_79@ }@H_502_79@
运行结果如下:

3,使用Upload Task来上传文件 28
sessionUpload(){@H_502_79@ //上传地址@H_502_79@ "http://hangge.com/upload.php"@H_502_79@ )@H_502_79@ //请求@H_502_79@ (url: url!,cachePolicy: .reloadIgnoringCacheData)@H_502_79@ request.httpMethod =@H_502_79@ "POST"@H_502_79@ @H_502_79@ //上传数据流@H_502_79@ documents =@H_502_79@ "/documents/1.png"@H_502_79@ imgData = try!@H_502_79@ Data@H_502_79@ (contentsOf:@H_502_79@ (fileURLWithPath: documents))@H_502_79@ @H_502_79@ uploadTask = session.uploadTask(with: request,from: imgData) {@H_502_79@ (data:@H_502_79@ URLResponse@H_502_79@ Error@H_502_79@ ?) ->@H_502_79@ VoID@H_502_79@ in@H_502_79@ //上传完毕后@H_502_79@ {@H_502_79@ @H_536_404@(error)@H_502_79@ {@H_502_79@ .utf8)@H_502_79@ "上传完毕:\(str)"@H_502_79@ )@H_502_79@ }@H_502_79@ }@H_502_79@ @H_502_79@ //使用resume方法启动任务@H_502_79@ uploadTask.resume()@H_502_79@ }@H_502_79@
附:服务端代码(upload.PHP) 26
<?PHP@H_502_79@ /** PHP 接收流文件@H_502_79@ * @param String $file 接收后保存的文件名@H_502_79@ * @return boolean@H_502_79@ */@H_502_79@ function@H_502_79@ receiveStreamfile(@H_502_79@ $receivefile@H_502_79@ ){@H_502_79@ @H_502_79@ $streamData@H_502_79@ = isset(@H_502_79@ $GLOBALS@H_502_79@ [@H_502_79@ 'HTTP_RAW_POST_DATA'@H_502_79@ ])?@H_502_79@ ] :@H_502_79@ ''@H_502_79@ ;@H_502_79@ @H_502_79@ @H_502_79@ if@H_502_79@ (@H_502_79@ empty@H_502_79@ (@H_502_79@ )){@H_502_79@ =@H_502_79@ file_get_contents@H_502_79@ (@H_502_79@ 'php://input'@H_502_79@ );@H_502_79@ @H_502_79@ }@H_502_79@ @H_502_79@ !=@H_502_79@ ){@H_502_79@ $ret@H_502_79@ file_put_contents@H_502_79@ else@H_502_79@ {@H_502_79@ = false;@H_502_79@ }@H_502_79@ return@H_502_79@ ;@H_502_79@ }@H_502_79@ //定义服务器存储路径和文件名@H_502_79@ =@H_502_79@ $_SERVER@H_502_79@ "document_ROOT"@H_502_79@ ].@H_502_79@ "/uploadfiles/hangge.png"@H_502_79@ ;@H_502_79@ = receiveStreamfile(@H_502_79@ );@H_502_79@ echo@H_502_79@ Json_encode(@H_502_79@ array@H_502_79@ 'success'@H_502_79@ =>(bool)@H_502_79@ ));@H_502_79@ ?>@H_502_79@
如何在上传时附带上文件名?
有时我们在文件上传的同时还会想要附带一些其它参数,比如文件名。这样服务端接收到文件后,就可以根据我们传过来的文件名来保存。实现这个其实很简单,客户端和服务端分别做如下修改。
客户端:将文件名以参数的形式跟在链接后面。比如:http://hangge.com/upload.PHP?filename=image1.png 服务端:通过$_GET["filename"]得到这个参数,并用其作为文件名保存。
原文出自: www.hangge.com 转载请保留原文链接: http://www.hangge.com/blog/cache/detail_780.html 总结

以上是内存溢出为你收集整理的Swift - 使用URLSession加载数据、下载、上传文件全部内容,希望文章能够帮你解决Swift - 使用URLSession加载数据、下载、上传文件所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1062124.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存