jueves, 12 de abril de 2012

Evitar que métodos que consumen mucho tiempo se ejecuten en el hilo principal

Si tenemos un método que pide y trae algo de la web, por ejemplo una imagen, sabemos que va a tardar mucho tiempo (unos segundos). Lo que conviene es crear una queue (una cola) para que esto corra en un hilo separado y no en el hilo principal que es donde se esta ejecutando la interfaz del usuario (UIKit queue).
Para esto usamos la API GCD (Grand Central Dispatch).
Este es un ejemplo de como hacerlo:

Este es el método sin crear una queue 

-(void) viewWillAppear:(BOOL)animated
{
    NSData  *imageData = [NSData dataWithContentsOfURL:networkURL]; 
    UIImage *image = [UIImage imageWithData:imageData];
    self.imageView.image = image;
    self.imageView.frame = CGRectMake(0, 0, image.size.width, image.size.heigh);
    self.scrollView.contentSize = image.size;
} 

Este es el método con la queue 

-(void) viewWillAppear:(BOOL)animated
{
    // Creo la queue
    dispatch_queue_t downloadQueue = dispatch_queue_create("image downloader", NULL);
    dispatch_async(downloadQueue, ^{
        
        NSData  *imageData = [NSData dataWithContentsOfURL:networkURL]; 
        
        //Llamadas al UIKit en el queue principal
        dispatch_async(dispatch_get_main_queue(), ^{
            UIImage *image = [UIImage imageWithData:imageData];
            self.imageView.image = image;
            self.imageView.frame = CGRectMake(0, 0, image.size.width, image.size.heigh);
            self.scrollView.contentSize = image.size;

        });
    });

    // Cuando no existan más bloques release
    dispatch_release(downloadQueue);
} 

lunes, 26 de marzo de 2012

Cambiar nombre de la aplicación

Para cambiar el nombre de la aplicación  hay que seleccionar el proyecto luego hacer doble click en Target y cambiamos el nombre. Luego en la pestaña Build Settings bajo el header Packaging cambiamos el nombre donde dice Product name, vamos al menú Product > Clean y luego Build.

jueves, 8 de marzo de 2012

Método para calcular los días, horas, minutos y segundos que faltan entre la fecha actual y otra futura


- (void) tiempoHasta:(NSString *) hasta {
    
    // Fecha actual
    NSDate *date = [NSDate date];
    int secondsNow =(int)[date timeIntervalSince1970];
   
    // Convierto el string hasta 
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyyMMdd"];
    NSDate *hastaDate = [dateFormat dateFromString:hasta]; 
    
    int secondsTarget=(int)[hastaDate timeIntervalSince1970];
    int differenceSeconds=secondsTarget-secondsNow;
    int days=(int)((double)differenceSeconds/(3600.0*24.00));
    int diffDay=differenceSeconds-(days*3600*24);
    int hours=(int)((double)diffDay/3600.00);
    int diffMin=diffDay-(hours*3600);
    int minutes=(int)(diffMin/60.0);
    int seconds=diffMin-(minutes*60);
}

jueves, 23 de febrero de 2012

Iconos para nuestra App

Conviene que el icono de nuestra aplicación lo hagamos de 512 x 512 pixels porque cuando subamos la aplicación a la AppleStore nos va a pedir una imagen de ese tamaño.
Además deberíamos crear imágenes con los siguientes tamaños para los distintos dispositivos:

Iphone: 57 x 57 pixels 
High Resolution Iphone/Ipod: 114 x114 pixels
Ipad: 72 x 72 pixels
High Resolution Ipad: 144 x 144 pixels

miércoles, 8 de febrero de 2012

Crear un botón por código

// Creo el boton y lo inicio con un frame que creo con la funcion CGRectMake.
UIButton *reservaButton = [[UIButton alloc] initWithFrame:CGRectMake(230, 45, 76, 25)];

// El boton tiene una imagen, la agrego como background
[reservaButton setBackgroundImage:[[UIImage imageNamed:@"reservar.png"] 
 stretchableImageWithLeftCapWidth:75.0 topCapHeight:0.0] 
                         forState:UIControlStateNormal];

// Enlazo el boton con el método reserve
[reservaButton addTarget:self 
                  action:@selector(reserve:)   
        forControlEvents:UIControlEventTouchUpInside];


martes, 31 de enero de 2012

Agregar pin a un mapa

Lo conveniente es crear una nueva clase que llamaremos Pin:
Pin.h

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

@interface Pin : NSObject{ 
    CLLocationCoordinate2D coordinate;        
    NSString *subtitle;        
    NSString *title;     
}
    
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic,retain)NSString *subtitle;
@property (nonatomic,retain) NSString *title;
- (id) initWithCoords:(CLLocationCoordinate2D) coords;

@end 

Pin.m
#import "Pin.h"
@implementation Pin
@synthesize coordinate;
@synthesize subtitle;
@synthesize title;

- (id) initWithCoords:(CLLocationCoordinate2D) coords{

    self = [super init];
    
    if (self != nil)
        coordinate = coords;
    
    return self;
}

- (void) dealloc{
    [title release];
    [subtitle release];
    [super dealloc];

}
@end


Luego agregamos al mapa el pin:
CLLocationCoordinate2D pinlocation;
pinlocation.latitude = latitude;
pinlocation.longitude  = longitude;
Pin *pin = [[Pin alloc] initWithCoords:pinlocation];
pin.title = self.tituloSel;
[mapa removeAnnotations:[mapa annotations]];
[mapa addAnnotation:pin];
[pin release];