Display images from mysql in xcode

0

I have a database with the table category in which has the image column with the URL of each image, how can I make them appear in the UIImage.

import Foundation
import UIKit
import WebKit

class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var tableView: UITableView!

    var values:NSArray = []

    var arr =  ["http://totalplanning.guiaparatuseventos.com/imagenes/subcategorias/cita-romantica%20(1).png","http://totalplanning.guiaparatuseventos.com/imagenes/salon.png","http://totalplanning.guiaparatuseventos.com/imagenes/curriculum-de-mujer.png","http://totalplanning.guiaparatuseventos.com/imagenes/belleza.png","http://totalplanning.guiaparatuseventos.com/imagenes/planeacion.png","http://totalplanning.guiaparatuseventos.com/imagenes/camara.png","http://totalplanning.guiaparatuseventos.com/imagenes/musica.png","http://totalplanning.guiaparatuseventos.com/imagenes/mobiliario.png","http://totalplanning.guiaparatuseventos.com/imagenes/familia.png"]

    //let colors = [UIColor.brownColor(),UIColor.purpleColor(), UIColor.yellowColor(), UIColor.greenColor(), UIColor.blueColor(), UIColor.grayColor()]

    override func viewWillAppear(animated: Bool) {

        super.viewWillAppear(animated)

        let proxyViewForStatusBar : UIView = UIView(frame: CGRectMake(0, 0,self.view.frame.size.width, 20))
        proxyViewForStatusBar.backgroundColor = hexStringToUIColor("#1C1C1C")
        self.view.addSubview(proxyViewForStatusBar)

        get();

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func hexStringToUIColor (hex:String) -> UIColor {
        var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet() as NSCharacterSet).uppercaseString

        if (cString.hasPrefix("#")) {
            cString = cString.substringFromIndex(cString.startIndex.advancedBy(1))
        }

        if ((cString.characters.count) != 6) {
            return UIColor.grayColor()
        }

        var rgbValue:UInt32 = 0
        NSScanner(string: cString).scanHexInt(&rgbValue)

        return UIColor(
            red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
            alpha: CGFloat(1.0)
        )
    }


    func get(){
        let url = NSURL(string:"PHP")
        let data = NSData(contentsOfURL: url!)

        values = ((try! NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)) as? NSArray)!

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return values.count

    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{

        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! SpecialCell

        let maindata = values[indexPath.row]

        cell.nombre.text = maindata["nombre"] as? String
        cell.descripcion.text = maindata["descripcion"] as? String

        let url = arr [indexPath.row]
        let urls = NSURL(string: url)
        let request: NSURLRequest = NSURLRequest(URL: urls!)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithRequest(request) {
            (data,response,error) -> Void in
            if ( error == nil && data != nil ) {
                func display_image() {
                    cell.imagen.image = UIImage(data: data!)
                }

                dispatch_async(dispatch_get_main_queue(), display_image)
            }
        }
        task.resume()

        let colors = [hexStringToUIColor("#FF0000"),hexStringToUIColor("#FF8000"),hexStringToUIColor("#FFFF00"),hexStringToUIColor("#80FF00"),hexStringToUIColor("00FFFF"),hexStringToUIColor("#0080FF"),hexStringToUIColor("#A901DB"),hexStringToUIColor("#FF00FF"),hexStringToUIColor("#FF0080")]

        cell.accessoryType = .DisclosureIndicator
        cell.imagen.backgroundColor = colors[indexPath.row % colors.count]

        return cell

    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        if (segue.identifier == "show") {

            if let indexPath = self.tableView.indexPathForSelectedRow
            {
                if let vc: ViewController = segue.destinationViewController as? ViewController {
                    vc.idCategoria = values[indexPath.item]["idCategoria"] as! String

                    print(vc.idCategoria)

                }

            }

        }

    }

}
    
asked by Brandon Josué Cerezo 12.08.2016 в 18:07
source

1 answer

1

First you need a way to get the information from the database to your app, for this you need a web service, it is recommended that it be of the REST type to make the communication more transparent and save bandwidth of the device. To make the call to the server you can do it in the following way:

//Variables globales
let apiUrl: String = "http://midominio.com/MiWebService"
var urlString: String = ""
var lstImagenes: [String] = []

    //Llamada al servidor
    let url = NSURL(string: apiUrl)!
    let session = NSURLSession.sharedSession()
    session.dataTaskWithURL(url, completionHandler: { (data:NSData?, response: NSURLResponse?,error: NSError?) -> Void in

        //Leer el JSON
        do{
            if let _ = NSString(data: data!, encoding: NSUTF8StringEncoding){

                //Parsear el JSON
                let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

                //Obtenemos la cantidad de imagenes
                let cantidadImagenes = jsonDictionary["count"] as! Int
                let imagenes = jsonDictionary["imagenes"] as! NSArray

                //Recorremos el arreglo de imagenes
                for(var i: Int = 0; i < cantidadImagenes; i++){
                    self.lstImagenes.append(imagenes[i] as! String)
                }

            }

        } catch{
            print("Ocurrio un error")
        }
    }).resume()

After we obtain the information from the web service we now use a library called AlamofireImage and Alamofire, these will help us with the management of the network and the memory of the telephone since they are in charge of making the asynchronous calls since our application is not locked when working with images from URL and store the cache of them. To show the images we do it in the following way, first we must import the libraries in our class. For this we must add references to our project that we can do from cocoapods or some form of what they tell us on their GitHub page.

Alamofire: link

AlamofireImage: link

import Alamofire
import AlamofireImage

Finally we send to call the method af_setImageWithURL of AlamofireImage in the following way assigning the UIImageView where we want to show it.

        //El arreglo lstImagenes contiene las URL's de las imagenes ejemplo: http://www.midominio.com/Imagenes/imagen01.jpg
        let urlImagen = NSURL(string: lstImagenes[indiceImagen])
        //imgImagen es mi UIImageView
        self.imgImagen.af_setImageWithURL(urlImagen!)

This code is tested with Swift 2.2 and IOS 9.3

UPDATE:

Method for uploading images:

//Carga las imagenes de forma asincrona
    func asyncImage(urlString: String, completionHandler:(image: UIImage?, url: String) -> ()) {

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {()in

            if let url = NSURL(string: urlString), let data = NSData(contentsOfURL: url), let image = UIImage(data: data) {
                dispatch_async(dispatch_get_main_queue(), {() in
                    completionHandler(image: image, url: urlString)
                })

            } else {

                dispatch_async(dispatch_get_main_queue(), {() in
                    completionHandler(image: nil, url: urlString)
                })

            }

        })

    }

Use of the method:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{



    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! SpecialCell

    let maindata = values[indexPath.row]

    cell.nombre.text = maindata["nombre"] as? String
    cell.descripcion.text = maindata["descripcion"] as? String

    let url = arr [indexPath.row]
    let urls = NSURL(string: url)
    let request: NSURLRequest = NSURLRequest(URL: urls!)
    let session = NSURLSession.sharedSession()

    //Uso del metodo asincrono
    asyncImage(urlString) { (image, url) -> () in
      cell.imagen.image = image
    }




   let colors = [hexStringToUIColor("#FF0000"),hexStringToUIColor("#FF8000"),hexStringToUIColor("#FFFF00"),hexStringToUIColor("#80FF00"),hexStringToUIColor("00FFFF"),hexStringToUIColor("#0080FF"),hexStringToUIColor("#A901DB"),hexStringToUIColor("#FF00FF"),hexStringToUIColor("#FF0080")]

    cell.accessoryType = .DisclosureIndicator
    cell.imagen.backgroundColor = colors[indexPath.row % colors.count]



    return cell



}
    
answered by 12.08.2016 / 20:14
source