[iOS] URLSession
DataTask
(1.) Closure
let url = URL(string: "http://opendata2.epa.gov.tw/UV/UV.json")
if let url = url {
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
//Do something...
}
task.resume()
}
(2.) Delegate
//session
URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)
//create Task
let task = session?.dataTask(with: request as URLRequest)
//delegate
extension FCNetworkManager: URLSessionTaskDelegate {
// DataTask 完成時
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
//Do something...
}
}
extension FCNetworkManager: URLSessionDataDelegate {
//appendData
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
//appendData
// receivedData!.append(data as Data)
}
}
DownloadTask
(1.) Closure
let url = URL(string: "http://opendata2.epa.gov.tw/UV/UV.json")
if let url = url {
let request = URLRequest(url: url)
let task = URLSession.shared.downloadTask(with: request) { (locationUrl, response, error) in
//Do Something...
}
task.resume()
}
(2.) Delegate
//session
URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)
//create Task
let task = session?.downloadTask(with: request as URLRequest)
//delegate
extension FCNetworkManager: URLSessionTaskDelegate {
// DownloadTask 完成時
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
//Do something...
}
}
extension FCNetworkManager: URLSessionDownloadDelegate {
//download完成的location, 在URLSessionTaskDelegate之前被呼叫
public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
//Do something...
}
//download progress
public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
//Do something...
}
}
UploadTask
(1.) Closure
let url = URL(string: "http://xxx.com/upload.php")
var request = URLRequest(url: url!, cachePolicy: .reloadIgnoringCacheData)
request.httpMethod = "POST"
let filePath = NSHomeDirectory() + "/Documents/image.png"
let imgData = try! Data(contentsOf: URL(fileURLWithPath: filePath))
_ = URLSession.shared.uploadTask(with: request, from: imgData) {
(data:Data?, response:URLResponse?, error:Error?) -> Void in
//Do something...
}
(2.) Delegate
Last updated