闽公网安备 35020302035485号
4.流任务(Stream tasks):处理流数据。
URLSessionConfiguration
URLSessionConfiguration 是 URLSession 的配置类,用于配置 URLSession 的行为,比如超时时间、缓存策略、代理设置等等。// 默认配置 let configuration = URLSessionConfiguration.default // 超时时间 configuration.timeoutIntervalForRequest = 15 configuration.timeoutIntervalForResource = 15 // 缓存策略 configuration.requestCachePolicy = .useProtocolCachePolicy // 请求头 configuration.httpAdditionalHeaders = ["Content-Type": "application/json"] // 是否允许蜂窝网络访问 configuration.allowsCellularAccess = true // 每个主机的最大连接数 configuration.httpMaximumConnectionsPerHost = 5 // 是否等待网络连接 configuration.waitsForConnectivity = true // 任务标识符 configuration.identifier = "com.example.app" // 网络服务类型 configuration.networkServiceType = .default // 是否等待网络连接 configuration.waitsForConnectivity = true // 创建 URLSession let session = URLSession(configuration: configuration)URLSessionDataTask
let url = URL(string: "https://api.github.com")!
let session = URLSession.shared
let task = session.dataTask(with: url) { data, response, error in
if let error = error {
print("请求出错 Error: \(error)")
return
}
if let response = response as? HTTPURLResponse {
print("状态码为: \(response.statusCode)")
}
if let data = data {
let str = String(data: data, encoding: .utf8)
print("请求 Response: \(str ?? "")")
}
}
task.resume()
这段代码创建了一个简单的 GET 请求,请求 GitHub 的 API,然后输出了响应的状态码和内容。这样就完成了一个简单的网络请求,是不是很简单呢?let url = URL(string: "https://api.github.com")!
let session = URLSession.shared
let fileURL = URL(fileURLWithPath: "path/to/file") // 上传文件的路径
let task = session.uploadTask(with: URLRequest(url: fileURL), fromFile: fileURL) { data, response, error in
if let error = error {
print("请求出错 Error: \(error)")
return
}
if let response = response as? HTTPURLResponse {
print("状态码为: \(response.statusCode)")
}
if let data = data {
let str = String(data: data, encoding: .utf8)
print("请求 Response: \(str ?? "")")
}
}
task.resume()
URLSessionDownloadTasklet url = URL(string: "https://api.github.com/xxx.json")!
let session = URLSession.shared
let task = session.downloadTask(with: url) { location, response, error in
if let error = error {
print("请求出错 Error: \(error)")
return
}
if let response = response as? HTTPURLResponse {
print("状态码为: \(response.statusCode)")
}
if let location = location {
let str = try? String(contentsOf: location)
// 保存在本地
let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let destinationURL = documentsURL.appendingPathComponent("downloadedFile")
try? fileManager.moveItem(at: location, to: destinationURL)
}
}
task.resume()
管理会话reset(completionHandler:):重置整个会话。
cancel():取消任务,取消后无法恢复,比如当用户离开这个页面的时候,可以把当前页面的网络请求取消,避免资源浪费。