Solución:
Puedes usar URL
, URLRequest
y URLSession
o NSURLConnection
como lo haría normalmente en Objective-C. Tenga en cuenta que para iOS 7.0 y posterior, URLSession
se prefiere.
Utilizando URLSession
Inicializar un URL
objeto y un URLSessionDataTask
de URLSession
. Luego ejecuta la tarea con resume()
.
let url = URL(string: "http://www.stackoverflow.com")!
let task = URLSession.shared.dataTask(with: url) (data, response, error) in
guard let data = data else return
print(String(data: data, encoding: .utf8)!)
task.resume()
Utilizando NSURLConnection
Primero, inicialice un URL
y un URLRequest
:
let url = URL(string: "http://www.stackoverflow.com")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
Luego, puede cargar la solicitud de forma asincrónica con:
NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main) (response, data, error) in
guard let data = data else return
print(String(data: data, encoding: .utf8)!)
O puede inicializar un NSURLConnection
:
let connection = NSURLConnection(request: request, delegate:nil, startImmediately: true)
Solo asegúrese de configurar su delegado en algo diferente a nil
y utilizar los métodos de delegado para trabajar con la respuesta y los datos recibidos.
Para obtener más detalles, consulte la documentación del NSURLConnectionDataDelegate
protocolo
Prueba en un patio de juegos de Xcode
Si desea probar este código en un campo de juegos de Xcode, agregue import PlaygroundSupport
a su patio de recreo, así como la siguiente convocatoria:
PlaygroundPage.current.needsIndefiniteExecution = true
Esto le permitirá utilizar código asincrónico en parques infantiles.
Verifique los siguientes códigos:
1. SynchonousRequest
Swift 1.2
let urlPath: String = "YOUR_URL_HERE"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSURLRequest = NSURLRequest(URL: url)
var response: AutoreleasingUnsafeMutablePointer=nil
var dataVal: NSData = NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)!
var err: NSError
println(response)
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary
println("Synchronous(jsonResult)")
Swift 2.0 +
let urlPath: String = "YOUR_URL_HERE"
let url: NSURL = NSURL(string: urlPath)!
let request1: NSURLRequest = NSURLRequest(URL: url)
let response: AutoreleasingUnsafeMutablePointer=nil
do
let dataVal = try NSURLConnection.sendSynchronousRequest(request1, returningResponse: response)
print(response)
do
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary
print("Synchronous(jsonResult)")
catch let error as NSError
print(error.localizedDescription)
catch let error as NSError
print(error.localizedDescription)
2. Solicitud asíncrona
Swift 1.2
let urlPath: String = "YOUR_URL_HERE"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSURLRequest = NSURLRequest(URL: url)
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler: (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println("Asynchronous(jsonResult)")
)
Swift 2.0 +
let urlPath: String = "YOUR_URL_HERE"
let url: NSURL = NSURL(string: urlPath)!
let request1: NSURLRequest = NSURLRequest(URL: url)
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler: (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
do
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary
print("ASynchronous(jsonResult)")
catch let error as NSError
print(error.localizedDescription)
)
3. Como conexión de URL habitual
Swift 1.2
var dataVal = NSMutableData()
let urlPath: String = "YOUR URL HERE"
var url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
connection.start()
Luego
func connection(connection: NSURLConnection!, didReceiveData data: NSData!)
self.dataVal?.appendData(data)
func connectionDidFinishLoading(connection: NSURLConnection!)
var error: NSErrorPointer=nil
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal!, options: NSJSONReadingOptions.MutableContainers, error: error) as NSDictionary
println(jsonResult)
Swift 2.0 +
var dataVal = NSMutableData()
let urlPath: String = "YOUR URL HERE"
var url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
connection.start()
Luego
func connection(connection: NSURLConnection!, didReceiveData data: NSData!)
dataVal.appendData(data)
func connectionDidFinishLoading(connection: NSURLConnection!)
do
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary
print(jsonResult)
catch let error as NSError
print(error.localizedDescription)
4. Solicitud POST asíncrona
Swift 1.2
let urlPath: String = "YOUR URL HERE"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request1.HTTPMethod = "POST"
var stringPost="deviceToken=123456" // Key and Value
let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)
request1.timeoutInterval = 60
request1.HTTPBody=data
request1.HTTPShouldHandleCookies=false
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler: (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println("AsSynchronous(jsonResult)")
)
Swift 2.0 +
let urlPath: String = "YOUR URL HERE"
let url: NSURL = NSURL(string: urlPath)!
let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request1.HTTPMethod = "POST"
let stringPost="deviceToken=123456" // Key and Value
let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)
request1.timeoutInterval = 60
request1.HTTPBody=data
request1.HTTPShouldHandleCookies=false
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler: (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
do
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary
print("ASynchronous(jsonResult)")
catch let error as NSError
print(error.localizedDescription)
)
5. Solicitud GET asíncrona
Swift 1.2
let urlPath: String = "YOUR URL HERE"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request1.HTTPMethod = "GET"
request1.timeoutInterval = 60
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler: (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println("AsSynchronous(jsonResult)")
)
Swift 2.0 +
let urlPath: String = "YOUR URL HERE"
let url: NSURL = NSURL(string: urlPath)!
let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request1.HTTPMethod = "GET"
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler: (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
do
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary
print("ASynchronous(jsonResult)")
catch let error as NSError
print(error.localizedDescription)
)
6. Carga de imagen (archivo)
Swift 2.0 +
let mainURL = "YOUR_URL_HERE"
let url = NSURL(string: mainURL)
let request = NSMutableURLRequest(URL: url!)
let boundary = "78876565564454554547676"
request.addValue("multipart/form-data; boundary=(boundary)", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST" // POST OR PUT What you want
let session = NSURLSession(configuration:NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: nil)
let imageData = UIImageJPEGRepresentation(UIImage(named: "Test.jpeg")!, 1)
var body = NSMutableData()
body.appendData("--(boundary)rn".dataUsingEncoding(NSUTF8StringEncoding)!)
// Append your parameters
body.appendData("Content-Disposition: form-data; name="name"rnrn".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("PREMKUMARrn".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
body.appendData("--(boundary)rn".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition: form-data; name="description"rnrn".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("IOS_DEVELOPERrn".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
body.appendData("--(boundary)rn".dataUsingEncoding(NSUTF8StringEncoding)!)
// Append your Image/File Data
var imageNameval = "HELLO.jpg"
body.appendData("--(boundary)rn".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition: form-data; name="profile_photo"; filename="(imageNameval)"rn".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Type: image/jpegrnrn".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(imageData!)
body.appendData("rn".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("--(boundary)--rn".dataUsingEncoding(NSUTF8StringEncoding)!)
request.HTTPBody = body
let dataTask = session.dataTaskWithRequest(request) (data, response, error) -> Void in
if error != nil
//handle error
else
let outputString : NSString = NSString(data:data!, encoding:NSUTF8StringEncoding)!
print("Response:(outputString)")
dataTask.resume()
Otra opcion es la Alamofire lib que ofrece métodos de solicitud / respuesta encadenables.
https://github.com/Alamofire/Alamofire
Hacer una solicitud
import Alamofire
Alamofire.request(.GET, "http://httpbin.org/get")
Manejo de respuestas
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
.response request, response, data, error in
print(request)
print(response)
print(error)
Tienes la opción de añadir valor a nuestro contenido cooperando tu veteranía en las referencias.