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

原文出自:www.hangge.com 转载请保留原文链接:http://www.hangge.com/blog/cache/detail_780.html
NSURLSession类支持三种类型的任务:加载数据、下载和上传。下面通过样例分别进行介绍。
1,使用Data Task加载数据
使用全局的sharedSession()和dataTaskWithRequest方法创建。

func sessionLoadData(){
    //创建NSURL对象
    let urlString:String="http://hangge.com"
    let url:NSURL! = NSURL(string:urlString)
    //创建请求对象
    let request:NSURLRequest = NSURLRequest(URL: url)

    let session = NSURLSession.sharedSession()

    let dataTask = session.dataTaskWithRequest(request,
        completionHandler: {(data, response, error) -> Void in
            if error != nil{
                print(error?.code)
                print(error?.description)
            }else{
                let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print(str)
            }
    }) as NSURLSessionTask

    //使用resume方法启动任务
    dataTask.resume() 
}

2,使用Download Task来下载文件
(1)不需要获取进度
使用sharedSession()和downloadTaskWithRequest方法即可

func sessionSimpleDownload(){
    //下载地址
    let url = NSURL(string: "http://hangge.com/blog/images/logo.png")
    //请求
    let request:NSURLRequest = NSURLRequest(URL: url!)

    let session = NSURLSession.sharedSession()

    //下载任务
    let downloadTask = session.downloadTaskWithRequest(request,
        completionHandler: { (location:NSURL?, response:NSURLResponse?, error:NSError?)
            -> Void in
            //输出下载文件原来的存放目录
            print("location:\(location)")
            //location位置转换
            let locationPath = location!.path
            //拷贝到用户目录
            let documnets:String = NSHomeDirectory() + "/Documents/1.png"
            //创建文件管理器
            let fileManager:NSFileManager = NSFileManager.defaultManager()
            try! fileManager.moveItemAtPath(locationPath!, toPath: documnets)
            print("new location:\(documnets)")
    })

    //使用resume方法启动任务
    downloadTask.resume()
}

(2)实时获取进度
需要使用自定义的NSURLSession对象和downloadTaskWithRequest方法

import UIKit

class ViewController: UIViewController ,NSURLSessionDownloadDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        sessionSeniorDownload()
    }

    //下载文件
    func sessionSeniorDownload(){
        //下载地址
        let url = NSURL(string: "http://hangge.com/blog/images/logo.png")
        //请求
        let request:NSURLRequest = NSURLRequest(URL: url!)

        let session = currentSession() as NSURLSession

        //下载任务
        let downloadTask = session.downloadTaskWithRequest(request)

        //使用resume方法启动任务
        downloadTask.resume()
    }

    //创建一个下载模式
    func currentSession() -> NSURLSession{
        var predicate:dispatch_once_t = 0
        var currentSession:NSURLSession? = nil

        dispatch_once(&predicate, {
            let config = NSURLSessionConfiguration.defaultSessionConfiguration()
            currentSession = NSURLSession(configuration: config, delegate: self,
                delegateQueue: nil)
        })
        return currentSession!
    }

    //下载代理方法,下载结束
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask,
        didFinishDownloadingToURL location: NSURL) {
            //下载结束
            print("下载结束")

            //输出下载文件原来的存放目录
            print("location:\(location)")
            //location位置转换
            let locationPath = location.path
            //拷贝到用户目录
            let documnets:String = NSHomeDirectory() + "/Documents/2.png"
            //创建文件管理器
            let fileManager:NSFileManager = NSFileManager.defaultManager()
            try! fileManager.moveItemAtPath(locationPath!, toPath: documnets)
            print("new location:\(documnets)")
    }

    //下载代理方法,监听下载进度
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask,
        didWriteData bytesWritten: Int64, totalBytesWritten: Int64,
        totalBytesExpectedToWrite: Int64) {
            //获取进度
            let written:CGFloat = (CGFloat)(totalBytesWritten)
            let total:CGFloat = (CGFloat)(totalBytesExpectedToWrite)
            let pro:CGFloat = written/total
            print("下载进度:\(pro)")
    }

    //下载代理方法,下载偏移
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask,
        didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
            //下载偏移,主要用于暂停续传
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

3,使用Upload Task来上传文件

func sessionUpload(){
    //上传地址
    let url = NSURL(string: "http://hangge.com/upload.php")
    //请求
    let request = NSMutableURLRequest(URL: url!)
    request.HTTPMethod = "POST"
    request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

    let session = NSURLSession.sharedSession()

    //上传数据流
    let documents =  NSHomeDirectory() + "/Documents/1.png"
    let imgData = NSData(contentsOfFile: documents)


    let uploadTask = session.uploadTaskWithRequest(request, fromData: imgData) {
        (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
        //上传完毕后
        if error != nil{
            print(error?.code)
            print(error?.description)
        }else{
            let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("上传完毕:\(str)")
        }
    }

    //使用resume方法启动任务
    uploadTask.resume()
}

附:服务端代码(upload.php)

<?php 
/** php 接收流文件
* @param  String  $file 接收后保存的文件名
* @return boolean
*/ 
function receiveStreamFile($receiveFile){   
    $streamData = isset($GLOBALS['HTTP_RAW_POST_DATA'])? $GLOBALS['HTTP_RAW_POST_DATA'] : ''; 

    if(empty($streamData)){ 
        $streamData = file_get_contents('php://input'); 
    } 

    if($streamData!=''){ 
        $ret = file_put_contents($receiveFile, $streamData, true); 
    }else{ 
        $ret = false; 
    } 

    return $ret;   
} 

//定义服务器存储路径和文件名
$receiveFile =  $_SERVER["DOCUMENT_ROOT"]."/uploadFiles/hangge.png"; 
$ret = receiveStreamFile($receiveFile); 
echo json_encode(array('success'=>(bool)$ret)); 
?>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值