创建一个网络请求类
struct NetworkRequest {
static func Put(url:String, filePath:String, fileName:String, parameter:String, completionHandler: @escaping (_ data: Dictionary<String, Any>, _ error:String?) -> ()) {
print("Type: PUT")
print("URL: \(url)")
//1.创建URL
guard let url = URL(string: url) else { return }
//2.创建请求
var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.httpBody = parameter.data(using: .utf8)
//3.创建会话
let session = URLSession.shared
//4.创建数据任务
let fileUrl = URL(fileURLWithPath: filePath)
let dataTask = session.uploadTask(with: request, fromFile: fileUrl) { (data, response, error) in
if let error = error {
print("ERROR: \(error.localizedDescription)")
completionHandler(["":""], error.localizedDescription)
return
}
do{
//将二进制数据转换为字典对象
if let jsonObj:Dictionary<String, Any> = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions()) as? Dictionary<String, Any> {
print("Data: \(jsonObj)")
completionHandler(jsonObj,nil)
} else {
print("ERROR: 数据解析失败")
completionHandler(["":""], "数据解析失败")
}
} catch{
print("ERROR: 数据获取失败")
completionHandler(["":""], "数据获取失败")
}
}
//5.启动数据任务
dataTask.resume()
}
static func Delete(url:String, postData:Dictionary<String, String>, completionHandler: @escaping (_ data: Dictionary<String, Any>, _ error:String?) -> ()) {
print("Type: DELETE")
print("URL: \(url)")
//1.创建URL
guard let url = URL(string: url) else { return }
//2.创建请求
var request = URLRequest(url: url)
request.httpMethod = "DELETE"
//添加post数据
let postString = postData.compactMap({ (key, value) -> String in
return "\(key)=\(value)"
}).joined(separator: "&")
request.httpBody = postString.data(using: .utf8)
//3.创建会话
let session = URLSession.shared
//4.创建数据任务
let dataTask = session.dataTask(with: request) { (data, response, error) in
if let error = error {
print("ERROR: \(error.localizedDescription)")
completionHandler(["":""], error.localizedDescription)
return
}
do{
//将二进制数据转换为字典对象
if let jsonObj:Dictionary<String, Any> = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions()) as? Dictionary<String, Any> {
print("Data: \(jsonObj)")
completionHandler(jsonObj,nil)
} else {
print("ERROR: 数据解析失败")
completionHandler(["":""], "数据解析失败")
}
} catch{
print("ERROR: 数据获取失败")
completionHandler(["":""], "数据获取失败")
}
}
//5.启动数据任务
dataTask.resume()
}
static func Post(url:String, postData:Dictionary<String, String>, completionHandler: @escaping (_ data: Dictionary<String, Any>, _ error:String?) -> ()) {
print("Type: POST")
print("URL: \(url)")
//1.创建URL
guard let url = URL(string: url) else { return }
//2.创建请求
var request = URLRequest(url: url)
//设置请求类型
//request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
//添加post数据
let postString = postData.compactMap({ (key, value) -> String in
return "\(key)=\(value)"
}).joined(separator: "&")
request.httpBody = postString.data(using: .utf8)
//3.创建会话
let session = URLSession.shared
//4.创建数据任务
let dataTask = session.dataTask(with: request) { (data, response, error) in
if let error = error {
print("ERROR: \(error.localizedDescription)")
completionHandler(["":""], error.localizedDescription)
return
}
do{
//将二进制数据转换为字典对象
if let jsonObj:Dictionary<String, Any> = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions()) as? Dictionary<String, Any> {
print("Data: \(jsonObj)")
completionHandler(jsonObj,nil)
} else {
print("ERROR: 数据解析失败")
completionHandler(["":""], "数据解析失败")
}
} catch{
print("ERROR: 数据获取失败")
completionHandler(["":""], "数据获取失败")
}
}
//5.启动数据任务
dataTask.resume()
}
static func Get(url:String, completionHandler: @escaping (_ data: Dictionary<String, Any>, _ error:String?) -> ()) {
print("Type: GET")
print("URL: \(url)")
//1.创建URL
guard let url = URL(string: url) else { return }
//2.创建请求
var request = URLRequest(url: url)
request.httpMethod = "GET"
//3.创建会话
let session = URLSession.shared
//4.创建数据任务
let dataTask = session.dataTask(with: request) { (data, response, error) in
if let error = error {
print("ERROR: \(error.localizedDescription)")
completionHandler(["":""], error.localizedDescription)
return
}
do{
//将二进制数据转换为字典对象
if let jsonObj:Dictionary<String, Any> = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions()) as? Dictionary<String, Any> {
print("Data: \(jsonObj)")
completionHandler(jsonObj,nil)
} else {
print("ERROR: 数据解析失败")
completionHandler(["":""], "数据解析失败")
}
} catch{
print("ERROR: 数据获取失败")
completionHandler(["":""], "数据获取失败")
}
}
//5.启动数据任务
dataTask.resume()
}
static func Download(url:String, delegate:UIViewController) {
print("Type: Download")
print("URL: \(url)")
//1.创建URL
guard let url = URL(string: url) else { return }
//2.创建请求
let request = URLRequest(url: url)
//3.创建会话
guard let delegate = delegate as? URLSessionDownloadDelegate else {
return
}
let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)
//4.创建数据任务
let dataTask = session.downloadTask(with: request)
//5.启动数据任务
dataTask.resume()
}
}
使用
class ViewController: UIViewController, URLSessionDownloadDelegate {
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
print("filePath: \(location.path)")
do{
let data = try Data(contentsOf: location)
let image = UIImage(data: data)
DispatchQueue.main.async {
self.imageView.image = image
}
} catch {
print("error")
}
}
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let imgUrl = "http://img4.imgtn.bdimg.com/it/u=1459418186,3680921364&fm=26&gp=0.jpg"
let url = "http://www.antu58.club/router/index.php/BookList/rankList?type=1"
//GET 查
NetworkRequest.Get(url: url) { (data, error) in
if let err = error {
print(err)
} else {
dump(data)
let code:String = data["status"] as! String
print(code)
}
}
NetworkRequest.Download(url: imgUrl, delegate: self)
}
}