Tengo una clase que ejecuta una API a trevés de un URLSessionDataTask. Agregué un protocolo para poder monitorear si existe un error o respuesta de éxito.
Todo funciona muy bien cuando ejecuto los métodos GET y POST cuando el content-type es del tipo application/json.
import UIKit
protocol NetworkManagerDelegate{
func connectionSuccess(session: NetworkManager, response: Data, apiService: ApiService)
func connectionWithError(session: NetworkManager, error: String, apiService: ApiService)
}
class NetworkManager: NSObject, URLSessionDelegate, URLSessionDataDelegate {
var delegate: NetworkManagerDelegate?
var dataResponse: Data? //trama de bytes que se ha descargado en cada servicio
var dataTask: URLSessionDataTask?
let urlDomain: String = "http://127.0.0.1"
let client_id: String = "2"
let client_secret: String = "kjajsnfjdsfndjfndsjnfndsfnsjf"
let timeoutInterval: Double = 60
var apiService: ApiService = .unknown
func postCreateUser(withUserRegistration: UserRegistration){
apiService = .postUserRegistration
if dataTask != nil {
dataTask?.cancel()
}
let urlStr = "\(urlDomain)/api/users"
var jsonData: Data?
do{
jsonData = try JSONEncoder().encode(withUserRegistration)
//let jsonString = String(bytes: jsonData!, encoding: .utf8)
//print(jsonString ?? "")
} catch let jsonErr{
print("Error Encoding json:",jsonErr)
}
let headers = ["Content-Type":"application/json"]
executePostURL(urlStr: urlStr, jsonData: jsonData, headers: headers)
}
//MARK: - Ejecución método POST de la API
func executePostURL(urlStr: String, jsonData: Data?, headers: [String: String] ){
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: self, delegateQueue:.main)
var request = URLRequest(url: URL(string: urlStr)!)
var postheaders = request.allHTTPHeaderFields ?? [:]
for header in headers{
postheaders[header.key] = header.value
}
request.allHTTPHeaderFields = postheaders
request.httpMethod = "POST"
request.timeoutInterval = timeoutInterval
if jsonData != nil {
request.httpBody = jsonData!
}
dataResponse = Data() //Inicializa la trama
dataTask = session.dataTask(with: request) //Solicita la petición
dataTask?.resume() //comenzamos con la comunicación
}
//Descargamos tramas de bytes
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
dataResponse?.append(data)
}
//Finaliza la descarga
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if error == nil {
print("No hay error")
let jsonString = String(bytes: dataResponse!, encoding: .utf8)
print(jsonString ?? "")
delegate?.connectionSuccess(session: self, response: dataResponse!, apiService: apiService)
} else{
print("Error \(error!.localizedDescription)")
delegate?.connectionWithError(session: self, error: error!.localizedDescription, apiService: apiService)
}
}
}
Necesito modificar el programa para poder enviar imágenes, pero todo lo que he encontrado convierte la imagen en base64 y la adjunta al request. Según entiendo esto consume una cantidad muy grande de recursos y es el equivalente a enviar la cadena resultante (base64) en formato JSON.
Cree un nuevo método que recibe una instancia de ImageForPost que contiene la URL local del archivo, y los nombres del mismo
struct ImageForPost {
var image: UIImage
var url: URL
var key: String
var name: String
init(withKey: String, withImage: UIImage, withURL: URL, withName: String) {
self.key = withKey
self.image = withImage
self.url = withURL
self.name = withName
}
}
Este es el método que ejecuto desde mi vista
func postAdResources(withAdId: Int, withImagesForPost: [ImageForPost] ,withAccessToken: String){
apiService = .postAdResources
if dataTask != nil {
dataTask?.cancel()
}
let urlStr = "\(urlDomain)/api/ads/\(withAdId)/resources"
let headers = ["Authorization":"Bearer " + withAccessToken, "Content-Type":"multipart/form-data", "Accept":"application/json"]
executePostURL(urlStr: urlStr, withImagesForPost: withImagesForPost, headers: headers)
}
Y este es el método que atiende la petición con el URLSessionDataTask
//MARK: - Ejecución método POST de la API con Imagenes
func executePostURL(urlStr: String, withImagesForPost: [ImageForPost]?, headers: [String: String] ){
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: self, delegateQueue:.main)
var request = URLRequest(url: URL(string: urlStr)!)
var postheaders = request.allHTTPHeaderFields ?? [:]
for header in headers{
postheaders[header.key] = header.value
}
request.allHTTPHeaderFields = postheaders
request.httpMethod = "POST"
request.timeoutInterval = timeoutInterval
if withImagesForPost != nil {
for image in withImagesForPost!{
request.setValue(image.key, forHTTPHeaderField: image.name)
request.httpBodyStream = InputStream.init(url: image.url)
}
}
dataResponse = Data() //Inicializa la trama
dataTask = session.uploadTask(withStreamedRequest: request) //Solicita la petición
dataTask?.resume() //comenzamos con la comunicación
}