欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 艺术 > iOS中URLSeesion的使用

iOS中URLSeesion的使用

2025/4/27 16:13:03 来源:https://blog.csdn.net/hthutao/article/details/144173689  浏览:    关键词:iOS中URLSeesion的使用

基本步骤

写过ios网络请求的都知道,URLSession就是关于用于发送网络请求,其基本原理就是通过创建task使用task来实现请求。步骤大致如下所示:
(1)创建一个URLSession对象

(2)使用URLSession建立一个task实例

(3)启动task实例(resume方法)

Session的创建

创建session实例有两种方法:
·默认session对象(shared)

·自定义配置对象(Configuration)

 var sharedSession = URLSession.shared//创建share对象 //创建configuration对象var config = URLSessionConfiguration.default//需要先创建配置对象var configuration  = URLSession(configuration:config)//配置代理的创建方式vae session = URLSession(configuration: config, delegate: self as! URLSessionDelegate, delegateQueue: nil)

关于第三种代创建方式,后面再讲(有关代理配置)

这样我们就可以创建最简单的一个Task请求了(好像有点看不懂,还是细说吧)

do{let request =  try URLRequest(url: URL(string:"https://httpbin.org/get")!, method: .get)let task = shared.dataTask(with: request){ (data,response,error) inif let result = try? JSONSerialization.jsonObject(with: data!,options: .allowFragments){print(result)}}task.resume()}catch{print("发生错误")print(error)}

会话类型

实际上session的会话类型分为以下三种

(1)默认会话模式(default):基于磁盘缓存的持久策略。这个模式共享cookie,缓存和证书,share就是该模式,configuration可以进行更多的配置,shared不支持。

(2)瞬时会话模式(ephemeral): 所有数据保存到内存中,session结束后,缓存数据也背清空。

(3)后台会话模式(bacjground): 将上传和下载移交到后台处理,需要一个identifier标识别。

let configDefault = URLSessionConfiguration.default
let congifEphemral = URLSessionConfiuratoin.ephemeral
let configBackground = URLSessionConfiguration.background(withIdentifier: "id")

创建了COnfiguration之后我们就可以配置他的他的各种属性,请求时间什么的,这里就不细说了,可以看官方文档。

URLSessionTask

URLSessionTask是表示任务对象的抽象,可以通过Session的实例上来调用Task一共有四种形式

1 : URLSessionDataTask:用于从服务器下载数据或上传数据到服务器。通常用于发送HTTP GET或者POST请求,并处理服务器响应的数据。

·数据从内存中处理

·适合传输JSON、XML等较小数据

let url = URL(string: "https://api.example.com/data")!
let task = URLSession.shared.dataTask(with: url) { data, response, error inif let error = error {print("Error: \(error)")return}if let data = data {print("Received data: \(data)")}
}
task.resume()

在上传bodyData期间,session也会周期性调用他的代理方法,用来告知是否连接成功。

func urlSession(_ session: URLSession,dataTask: URLSessionDataTask,didReceive response: URLResponse,completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {print("接收到服务器的响应")// 必须设置对响应进行允许处理才会执行后面的操作completionHandler(.allow)
}func urlSession(_ session: URLSession,dataTask: URLSessionDataTask,didReceive data: Data) {//该方法可能被调用多次print("接受到服务器的数据")
}func urlSession(_ session: URLSession,task: URLSessionTask,didCompleteWithError error: Error?) {print("请求完成之后调用成功或者失败")
}

2:URLSessionDownloadTask

用于从服务器下载文件,存到磁盘的临时文件中。

·适合处理文件的下载

·自动管理进度,在后台也可以继续下载

do{let quest = URLRequest(url: URL(string:"https://img-home.csdnimg.cn/images/20241129103115.jpg")!)let task = session.downloadTask(with: quest){(location,response,error) in//location是tmp文件下的临时文件路径,随时可能会被删除,所以需要把下载的文件落到caches或者documents中let path = location!.pathlet documentts = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! + "/" + (response?.suggestedFilename)!do{try FileManager.default.moveItem(atPath: path, toPath: documentts)}catch {print(error)}}task.resume()}

在下载文件时候我们就可以用到之前所说的代理方法,就可以实时监控下载进度,控制文件下载等等。

//代理下载session = URLSession(configuration: URLSessionConfiguration.default,delegate: self as URLSessionDownloadDelegate,delegateQueue: OperationQueue.main)let request = URLRequest(url: URL(string: "https://dldir1.qq.com/qqfile/QQforMac/QQ_V5.5.1.dmg")!)let task = session.downloadTask(with: request)task.resume()}//下载过程中写入数据会一直调用这个方法//didWriteData:之前已经下载完的数据量//bytesWritten:本次写入的数据量//totalBytesWritten:目前总共写入的数据量//totalBytesExpectedToWrite:文件总数据量func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {let progress = Float(totalBytesWritten)/Float(totalBytesExpectedToWrite)print("进度为\(progress)")}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {print("下载完成")}

我么就可以通过代理回调中实时获取到下载进度.

3:URLSessionUploadTask:上传文件到服务器

let url = URL(string: "https://example.com/upload")!
var request = URLRequest(url: url)
request.httpMethod = "POST"let fileURL = URL(fileURLWithPath: "/path/to/file")
let task = URLSession.shared.uploadTask(with: request, fromFile: fileURL) { data, response, error inif let error = error {print("Error: \(error)")return}print("Upload complete")
}
task.resume()

4:URLSessionStreamTask

用于处理基于TCP或TLS的双向数据传输,实时数据传输

let host = "example.com"
let port = 8080let session = URLSession(configuration: .default)
let task = session.streamTask(withHostName: host, port: port)
task.resume()task.readData(ofMinLength: 1, maxLength: 1024, timeout: 10) { data, atEOF, error inif let error = error {print("Error: \(error)")return}if let data = data {print("Received data: \(data)")}
}task.write("Hello, server".data(using: .utf8)!, timeout: 10) { error inif let error = error {print("Error: \(error)")} else {print("Message sent")}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词