IOS网络、多线程、shareSDK- NSURLSession的使用

使用NSURLSession将地理坐标转换为地名

通过绘画对象,将地理坐标转换成地名。网址会话对象具有后台上传下载、暂停和恢复网络操作、丰富的代理模式等优点.

//
//  ViewController.swift
//  Dome2test
//
//  Created by 郭文亮 on 2018/11/22.
//  Copyright © 2018年 finalliang. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
    var label = UILabel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        label.frame = CGRect(x: 20, y: 40, width: 280, height: 500)
        label.text = "loading..."
        label.font = UIFont(name: "Arial", size: 14)
        label.numberOfLines = 0
        label.lineBreakMode = NSLineBreakMode.byWordWrapping
        self.view.addSubview(label)
        
        let url = URL(string: "http://gc.ditu.aliyun.com/regeocoding?l=34.350178,108.9493248&type=010")
        let request = URLRequest(url: url!, cachePolicy: .useProtocolCachePolicy
            , timeoutInterval: 30)
        let session = URLSession.shared
        let task = session.dataTask(with: request, completionHandler: {(data,response,error)
            -> Void in
            if error != nil {
                print(error.debugDescription)
            }else{
                let result = String(data: data!, encoding: String.Encoding.utf8)
                DispatchQueue.main.async(execute: {()-> Void in
                    self.label.text = result
                })
            }
        })
        task.resume()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

使用NSURLSession下载图片并写入文档


//
//  ViewController.swift
//  Dome2test
//
//  Created by 郭文亮 on 2018/11/22.
//  Copyright © 2018年 finalliang. All rights reserved.
//

import UIKit
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let url = URL(string: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1542861700007&di=2310d15b67cccd49a24921f380022ba3&imgtype=0&src=http%3A%2F%2Fimg.pconline.com.cn%2Fimages%2Fupload%2Fupc%2Ftx%2Fphotoblog%2F1708%2F23%2Fc4%2F56419133_1503466251515_mthumb.jpeg")
        let request = URLRequest(url: url!)
        let session = URLSession.shared
        //创建一个下载任务的网络请求
        let downloadTask = session.downloadTask(with: request, completionHandler: {(location:URL? ,response:URLResponse?, error:Error?)
            -> Void in
            do{
                //获得网络下载后 获得位于缓存目录的 图片原始存储路径
                let originalPath = location!.path
                print(originalPath)
                //存储目标位置
                let targetPath:String = NSHomeDirectory()+"/Documents/logo.jpeg"
                let fileManager:FileManager = FileManager.default
                try fileManager.moveItem(atPath: originalPath, toPath: targetPath)
                print(targetPath)
            }catch{
                print("Network error.")
            }
        })
        downloadTask.resume()
    
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

使用NSURLSession下载图片显示下载进度

尽量找一个质量高的图片。因为文件会大一点。否则下载太快看不到过程

//
//  ViewController.swift
//  Dome2test
//
//  Created by 郭文亮 on 2018/11/22.
//  Copyright © 2018年 finalliang. All rights reserved.
//

import UIKit
//添加一个下载代理协议 实施监测下载进度URLSessionDownloadDelegate
class ViewController: UIViewController , URLSessionDownloadDelegate{
    
    var backgroundView:UIView = UIView()
    var foregroundView:UIView = UIView()
    var projressLabel:UILabel = UILabel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        backgroundView.frame = CGRect(x: 16, y: 106, width: 288, height: 44)
        backgroundView.backgroundColor = UIColor.lightGray
        
        foregroundView.frame = CGRect(x: 20, y: 110, width: 0, height: 36)
        foregroundView.backgroundColor = UIColor.green
        
        projressLabel.frame = CGRect(x: 20, y: 160, width: 280, height: 36)
        projressLabel.textAlignment = NSTextAlignment.center
        
        self.view.addSubview(backgroundView)
        self.view.addSubview(foregroundView)
        self.view.addSubview(projressLabel)
        
        let url = URL(string: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1542867535636&di=bdeae863433e942906a6a9e26448467c&imgtype=0&src=http%3A%2F%2Fgss0.baidu.com%2F-Po3dSag_xI4khGko9WTAnF6hhy%2Fzhidao%2Fpic%2Fitem%2Fa8773912b31bb051db0967cf307adab44aede02c.jpg")
        let request = URLRequest(url: url!)
        //获得网址会话单例对象  程程会话单例对象的方法
        let session = self.buildSession() as Foundation.URLSession
        //创建一个下载任务的网络请求
        let downloadTask = session.downloadTask(with: request)
        downloadTask.resume()
    }
    func buildSession() -> Foundation.URLSession {
        var session: URLSession? = nil
        //获得网址会话配置的单例对象
        let config = URLSessionConfiguration.default
        //通过网址会话配置对象创建网址会话对象,并设置代理为当前视图对象 返回设置好的网址会话对象
        session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
        return  session!
    }
    //代理方法。响应下载完成的事件
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        //获得网络下载后 图片的原始存储路径。
        do {
            let oldPath = location.path
            print(oldPath)
            //创建一个目标文件地址。图片移动
            let targetPath:String = NSHomeDirectory()+"/Documents/test.png"
            let fileManager:FileManager = FileManager.default
            if !fileManager.fileExists(atPath: targetPath) {
                try fileManager.moveItem(atPath: oldPath, toPath: targetPath)
                print(targetPath)
            }
        } catch  {
            print("Network error.")
        }
    }
    //代理方法。响应下载中的变化
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        //计算从网络下载的数据量, 与总数的数据量的比值
        let rate: CGFloat = CGFloat(totalBytesWritten)/CGFloat(totalBytesExpectedToWrite)
        //从一个分离的先层呢 切换至主线  更新ui
        DispatchQueue.main.async(execute:{()in
            self.foregroundView.frame.size.width = rate * 280
            self.projressLabel.text = "\(totalBytesWritten)/\(totalBytesExpectedToWrite)"
        })
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

使用NSURLSession上传图片

通过网址会话对象,向远程服务器上传图片

//
//  ViewController.swift
//  Dome2test
//
//  Created by 郭文亮 on 2018/11/22.
//  Copyright © 2018年 finalliang. All rights reserved.
//

import UIKit
class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let url = URL(string: "http://www.coolketang.com/yourUploadingURL")
        let request = URLRequest(url: url!)
        let session = URLSession.shared
        //创建字符串作为等待上传的图片路径
        let image = NSHomeDirectory()+"/Documents/test.png"
        print(image)
        //将图片内容转换为二进制
        let imageData = try? Data(contentsOf: URL(fileURLWithPath: image))
        let task = session.uploadTask(with: request, from: imageData!, completionHandler: {(NSData,reponse:URLResponse?,error:Error?) -> Void in
            print("Uploading Finished")
        })
        task.resume()
    }

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值