URLSession类支持三种类型的任务:加载数据、下载和上传。下面通过样例分别进行介绍。(本文代码已升级至
Swift3)
运行结果如下:
2,使用Download Task来下载文件
(2)实时获取进度
需要使用自定义的 URLSession对象和 downloadTask方法
21
运行结果如下:
3,使用Upload Task来上传文件
28
附:服务端代码(upload.PHP)
26
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
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.shared和
downloadTask方法即可
运行结果如下:
|
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方法
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来上传文件
| 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()
}
|
<?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