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 sessionLoadData(){
//创建URL对象
let urlString = "http://hangge.com"
url = URL (string:urlString)
//创建请求对象
request = URLRequest (url: url!)
session = URLSession .shared
dataTask = session.dataTask(with: request,
completionHandler: {(data,response,error) -> Void in
if error != nil {
print (error.debugDescription)
} else {
str = String (data: data!,encoding: String . Encoding .utf8)
(str)
}
}) as URLSessionTask
//使用resume方法启动任务
dataTask.resume()
}
运行结果如下:

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 sessionSimpleDownload(){
//下载地址
let url = URL (string: "http://hangge.com/blog/images/logo.png" )
//请求
request = URLRequest (url: url!)
session = URLSession .shared
//下载任务
downloadTask = session.downloadTask(with: request,
completionHandler: { (location: ?,response: URLResponse ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,error: Error ?)
-> Void in
//输出下载文件原来的存放目录
print ( "location:\(location)" )
//location位置转换
locationPath = location!.path
//拷贝到用户目录
documnets: String = NSHomeDirectory () + "/Documents/1.png"
//创建文件管理器
fileManager = FileManager . default
try! fileManager.moveItem(atPath: locationPath,toPath: documnets)
"new location:\(documnets)" )
})
//使用resume方法启动任务
downloadTask.resume()
}
运行结果如下:


(2)实时获取进度
需要使用自定义的 URLSession对象和 downloadTask方法
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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 UIKit
class ViewController : UIViewController , URLSessionDownloadDelegate {
private lazy var session: = {
//只执行一次
config = URLSessionConfiguration . default
currentSession = (configuration: config,delegate: self ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,
delegateQueue: )
return currentSession
}()
override viewDidLoad() {
super .viewDidLoad()
sessionSeniorDownload()
}
//下载文件
sessionSeniorDownload(){
//下载地址
(string: "http://hangge.com/blog/images/logo.png" )
//请求
(url: url!)
//下载任务
downloadTask = session.downloadTask(with: request)
//使用resume方法启动任务
downloadTask.resume()
}
//下载代理方法,下载结束
urlSession(_ session: ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,downloadTask: URLSessionDownloadTask ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,
didFinishDownloadingTo location: ) {
//下载结束
( "下载结束" )
//输出下载文件原来的存放目录
"location:\(location)" )
//location位置转换
locationPath = location.path
//拷贝到用户目录
documnets: = NSHomeDirectory () + "/Documents/2.png"
//创建文件管理器
fileManager = FileManager default
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:0px 1em!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; min-height:auto!important; background:none rgb(249,toPath: documnets)
"new location:\(documnets)" )
}
//下载代理方法,监听下载进度
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:0px 1em!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; min-height:auto!important; background:none rgb(249,
didWriteData bytesWritten: Int64 ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,totalBytesWritten: ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,
totalBytesExpectedToWrite: ) {
//获取进度
written: CGFloat = ( )(totalBytesWritten)
total: = ( CGFloat )(totalBytesExpectedToWrite)
pro: = written/total
"下载进度:\(pro)" )
}
//下载代理方法,下载偏移
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:0px 1em!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; min-height:auto!important; background:none rgb(249,
didResumeAtOffset fileOffset: Int64 ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,expectedTotalBytes: ) {
//下载偏移,主要用于暂停续传
}
didReceiveMemoryWarning() {
.didReceiveMemoryWarning()
}
}
运行结果如下:

3,使用Upload Task来上传文件
28
sessionUpload(){
//上传地址
"http://hangge.com/upload.php" )
//请求
(url: url!,cachePolicy: .reloadIgnoringCacheData)
request.httpMethod = "POST"
//上传数据流
documents = "/Documents/1.png"
imgData = try! Data (contentsOf: (fileURLWithPath: documents))
uploadTask = session.uploadTask(with: request,from: imgData) {
(data: ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,response: URLResponse ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,error: Error ?) -> Void in
//上传完毕后
{
(error)
{
.utf8)
"上传完毕:\(str)" )
}
}
//使用resume方法启动任务
uploadTask.resume()
}
附:服务端代码(upload.PHP)
26
<?PHP
/** PHP 接收流文件
* @param String $file 接收后保存的文件名
* @return boolean
*/
function receiveStreamFile( $receiveFile ){
$streamData = isset( $GLOBALS [ 'HTTP_RAW_POST_DATA' ])? ] : '' ;
if ( empty ( )){
= file_get_contents ( 'php://input' );
}
!= ){
$ret file_put_contents PHP plain" style="outline:0px!important; border:0px!important; bottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas, PHP variable" style="outline:0px!important; border:0px!important; bottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,true);
} else {
= false;
}
return ;
}
//定义服务器存储路径和文件名
= $_SERVER "DOCUMENT_ROOT" ]. "/uploadFiles/hangge.png" ;
= receiveStreamFile( );
echo json_encode( array 'success' =>(bool) ));
?>
如何在上传时附带上文件名?
有时我们在文件上传的同时还会想要附带一些其它参数,比如文件名。这样服务端接收到文件后,就可以根据我们传过来的文件名来保存。实现这个其实很简单,客户端和服务端分别做如下修改。
  • 客户端:将文件名以参数的形式跟在链接后面。比如:http://hangge.com/upload.PHP?fileName=image1.png
  • 服务端:通过$_GET["fileName"]得到这个参数,并用其作为文件名保存。

原文出自: www.hangge.com 转载请保留原文链接: http://www.hangge.com/blog/cache/detail_780.html

Swift - 使用URLSession加载数据、下载、上传文件的更多相关文章

  1. 用canvas做一个DVD待机动画的实现代码

    这篇文章主要介绍了用canvas做一个DVD待机动画的实现代码的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  2. 使用Html5多媒体实现微信语音功能

    这篇文章主要介绍了使用Html5多媒体实现微信语音功能,需要的朋友可以参考下

  3. HTML5 播放 RTSP 视频的实例代码

    目前大多数网络摄像头都是通过 RTSP 协议传输视频流的,但是 HTML 并不标准支持 RTSP 流。本文重点给大家介绍HTML5 播放 RTSP 视频的实例代码,需要的朋友参考下吧

  4. HTML5自定义视频播放器源码

    这篇文章主要介绍了HTML5自定义视频播放器源码,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下

  5. Html5 滚动穿透的方法

    这篇文章主要介绍了Html5 滚动穿透的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  6. HTML5自定义mp3播放器源码

    这篇文章主要介绍了HTML5自定义mp3播放器源码,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下

  7. 详解HTML5中CSS外观属性

    这篇文章主要介绍了HTML5中CSS外观属性的相关知识,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,,需要的朋友可以参考下

  8. CSS中实现动画效果-附案例

    这篇文章主要介绍了 CSS中实现动画效果并附上案例代码及实现效果,就是CSS动画样式处理,动画声明需要使用@keyframes name,后面的name是人为定义的动画名称,下面我们来看看文章的具体实现内容吧,需要的小伙伴可以参考一下

  9. html5默认气泡修改的代码详解

    这篇文章主要介绍了html5默认气泡修改的代码详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  10. 浅析HTML5中的download属性使用

    这篇文章主要介绍了浅析HTML5中的download属性使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

随机推荐

  1. Swift UITextField,UITextView,UISegmentedControl,UISwitch

    下面我们通过一个demo来简单的实现下这些控件的功能.首先,我们拖将这几个控件拖到storyboard,并关联上相应的属性和动作.如图:关联上属性和动作后,看看实现的代码:

  2. swift UISlider,UIStepper

    我们用两个label来显示slider和stepper的值.再用张图片来显示改变stepper值的效果.首先,这三个控件需要全局变量声明如下然后,我们对所有的控件做个简单的布局:最后,当slider的值改变时,我们用一个label来显示值的变化,同样,用另一个label来显示stepper值的变化,并改变图片的大小:实现效果如下:

  3. preferredFontForTextStyle字体设置之更改

    即:

  4. Swift没有异常处理,遇到功能性错误怎么办?

    本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请发送邮件至dio@foxmail.com举报,一经查实,本站将立刻删除。

  5. 字典实战和UIKit初探

    ios中数组和字典的应用Applicationschedule类别子项类别名称优先级数据包contactsentertainment接触UIKit学习用Swift调用CocoaTouchimportUIKitletcolors=[]varbackView=UIView(frame:CGRectMake(0.0,0.0,320.0,CGFloat(colors.count*50)))backView

  6. swift语言IOS8开发战记21 Core Data2

    上一话中我们简单地介绍了一些coredata的基本知识,这一话我们通过编程来实现coredata的使用。还记得我们在coredata中定义的那个Model么,上面这段代码会加载这个Model。定义完方法之后,我们对coredata的准备都已经完成了。最后强调一点,coredata并不是数据库,它只是一个框架,协助我们进行数据库操作,它并不关心我们把数据存到哪里。

  7. swift语言IOS8开发战记22 Core Data3

    上一话我们定义了与coredata有关的变量和方法,做足了准备工作,这一话我们来试试能不能成功。首先打开上一话中生成的Info类,在其中引用头文件的地方添加一个@objc,不然后面会报错,我也不知道为什么。

  8. swift实战小程序1天气预报

    在有一定swift基础的情况下,让我们来做一些小程序练练手,今天来试试做一个简单地天气预报。然后在btnpressed方法中依旧增加loadWeather方法.在loadWeather方法中加上信息的显示语句:运行一下看看效果,如图:虽然显示出来了,但是我们的text是可编辑状态的,在storyboard中勾选Editable,再次运行:大功告成,而且现在每次单击按钮,就会重新请求天气情况,大家也来试试吧。

  9. 【iOS学习01】swift ? and !  的学习

    如果不初始化就会报错。

  10. swift语言IOS8开发战记23 Core Data4

    接着我们需要把我们的Rest类变成一个被coredata管理的类,点开Rest类,作如下修改:关键字@NSManaged的作用是与实体中对应的属性通信,BinaryData对应的类型是NSData,CoreData没有布尔属性,只能用0和1来区分。进行如下操作,输入类名:建立好之后因为我们之前写的代码有些地方并不适用于coredata,所以编译器会报错,现在来一一解决。

返回
顶部