Singleton en Objective-c

Uno de los patrones de diseño mas utilizados es el singleton. El singleton es usado para instanciar solo una vez una clase. Encontre un template para un singleton en objective-c el cual quiero compartir con ustedes.

Pero para este caso usare un singleton para guardar/retener un valor de tipo NSString

A continuación pongo el código para el singleton.

MySingleton.h

#import <Foundation/Foundation.h>

@interface MySingleton : NSObject {

    NSString *stringValue;

}

+ (MySingleton *)sharedMySingleton;

- (NSString *)stringValue;
- (void)setStringValue:(NSString *)value;

@end

MySingleton.m

#import "MySingleton.h"

@implementation MySingleton

static MySingleton* _sharedMySingleton = nil;

+(MySingleton*)sharedMySingleton
{
	@synchronized([MySingleton class])
	{
		if (!_sharedMySingleton)
			[[self alloc] init];

		return _sharedMySingleton;
	}

	return nil;
}

+(id)alloc
{
	@synchronized([MySingleton class])
	{
		NSAssert(_sharedMySingleton == nil, @"Attempted to allocate a second instance of a singleton.");
		_sharedMySingleton = [super alloc];
		return _sharedMySingleton;
	}

	return nil;
}

-(id)init {
	self = [super init];
	if (self != nil) {
		// initialize stuff here
        stringValue = nil;
	}

	return self;
}

- (NSString *)stringValue{
    return stringValue;
}
- (void)setStringValue:(NSString *)value{
    stringValue = value;
}

@end

Si quieres Guardar(Set) el stringValue, usamos lo siguiente:

[[MySingleton sharedMySingleton] setStringValue:@"Hello World"];

Y si quieres obtener(Get) el stringValue, usamos lo siguiente:

[[MySingleton sharedMySingleton] stringValue];

Puedes descargar una copia de un código funcional de github

Fuente del Post : getsetgames

Como Guardar, Cargar o Borrar Imagenes de iPhone/iPad documents directory

Si en tu proyecto tienes la necesidad de cargar imagenes desde la web, sugiero que salves las imagenes dentro documents directory del tu iPhone/iPad , esto para optimizar la aplicacion y el performance.

Para guardar, cargar o eliminar una imagen del directorio de documentos de tu app, lo hacemos con 3 simples metodos.

Para Guardar una imagen

- (void)saveImage:(UIImage*)image:(NSString*)imageName {

NSData *imageData = UIImagePNGRepresentation(image);//convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageName]];

[fileManager createFileAtPath:fullPath contents:imageData attributes:nil];
NSLog(@"image saved");
}

Para Eliminar una imagen

- (void)removeImage:(NSString*)fileName {

NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", fileName]];

[fileManager removeItemAtPath: fullPath error:NULL];
NSLog(@"image removed");

}

Para Cargar una imagen

- (UIImage*)loadImage:(NSString*)imageName {

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat:@"%@.png", imageName]];

return [UIImage imageWithContentsOfFile:fullPath];

}

Ahora, para salvar cualquier imagen solo llamas al metodo algo asi;

[self saveImage: theUIImage: @"UIImageName"];

o para cargar:

myUIImage = [self loadImage: @"UIImageName"];

o para eliminar:

[self removeImage: @"UIImageName"];

Obtener una imagen desde una url:

NSString *urlName= @"http://theURL/image";
NSURL *url = [NSURL URLWithString:urlName];
UIImage *myImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];

Incorporar Youtube Video en iPad

Here I put a small tutorial for embedded a youtube video on iPad also works on iPhone.

Note: The iPad/iPhone simulator does not allow online reproduction, the video will only be visible in a real device .

  1. First we create a View-based Application project.
  2. I will name it EmbeddedVideo, you can name it whatever you like.
  3. Open the EmbeddedVideoViewController.xib and added a UIWebView(drag and drop).

  4. Then in EmbeddedVideoViewController.h create an IBOutlet for ourUIWebView, leaving something like this:
    @interface EmbeddedVideoViewController : UIViewController {
       UIWebView *webVideo;
    }
    
    @property (nonatomic, retain) IBOutlet UIWebView *webVideo;
    
    @end
  5. We connect the IBOutlet with UIWebView, open the  EmbeddedVideoViewController.xib and  in File’s Owner in the Outlets section select/drag on our UIWebView:
  6. We opened in EmbeddedVideoViewController.m within viewDidLoad method (if commented, uncomment it) add a few lines of code, something like this:
    - (void)viewDidLoad
    {
           [super viewDidLoad];
           NSString *videoURL = @"http://www.youtube.com/watch?v=JOddp-nlNvQ";
           NSString *htmlString =[[NSString alloc] initWithFormat:@" ",videoURL];
           [webVideo setAllowsInlineMediaPlayback:YES];
           [webVideo loadHTMLString:htmlString baseURL:nil];
    }
  7. After that compile and run on our device and we’ll see something like this

I hope this will be useful and you can download the code from  here

Encriptar string con SHA1 en iPhone/iPad (obective-c)

Navegando por internet encontre el siguiente codigo que permite encriptar un string usando SHA1.

Primero necesitamos incluir la libreria de CommonCrypto para esto agregamos la siguiente linea:

 #import <CommonCrypto/CommonDigest.h>

y despues agregamos el siguiente metodo a nuestro codigo:

-(NSString*) digest:(NSString*)input
{

    NSData *data = [input dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(data.bytes, data.length, digest);
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];

    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];

    return output;

}

El codigo anterior recibe un string de parametro y regresa el mismo string pero encriptado con SHA1

Pueden descargar un ejemplo funcional para iphone de gitHub

No se puede obtener acceso a C:\windowssystem32config systemprofileDesktop

Despues de desintalar un antivirus a Windows, recivia este mensaje:
No se puede obtener acceso a C:\windowssystem32configsystemprofileDesktop

Para solucionar lo anterior hacemos lo siguiente:

1-. Vamos a la ruta que nos indica el error “C:\windowssystem32configsystemprofile” y borramos la carpeta de Desktop que se encuentra alli.

2-. Despues vamos a la carpeta de usuario copiamos la carpeta de Desktop y la pegamos en el lugar donde borramos la anterior en “C:\windowssystem32configsystemprofile”

Reiniciamos y con eso se solucionara.

Fuente: forums.techguy.org

“You are not allowed to call this page directly”

You are not allowed to call this page directly” — Este mensaje me aparecía al querer actualizar directamente desde WordPress y en un incio pensaba que el error estaba en los permisos de “update-core.php”, pero no era asi el error es el plugin de NextGEN ImageFlow.

Solo hay que desactivar el plugin de NextGEN ImageFlow, y ya va funcionar la seccion de actualizar en WordPress

Fuente
WordPress Support

Borrar la última revisión de un repositorio Subversion

EL día de hoy alguien hizo un commit a un repositorio y esta estaba corrompida o en conflicto, lo que nos afecto todos lo que trabajamos en ese proyecto.
La solución hacer un dump de los repositorio para así eliminar la última revisión en el Subversion.

1. Hacer un dump del repositorio de la primera a la penúltima revisión. El mi repositorio tenemos un proyecto con 7 revisiones(incluyendo la corrompida), para mi caso haría un dump de la 1 a la 6. En la terminal quedaría algo así:
sudo svnadmin dump /svn/nombre-repositorio -r 1:6 > repositorio.dump

2. Borráramos el repositorio
sudo rm -rf /svn/directorio-repositorio

3.Crear de nuevo el repositorio
sudo svnadmin create /svn/nombre-repositorio

4. Cargamos el “repositorio.dump” al repositorio que acabamos de hacer
sudo svnadmin load /svn/nombre-repositorio < repositorio.dump

Y con eso eliminaremos la ultima revisión arreglando, nuestro conflicto.

Instalar OpenSSH Server en Ubuntu

En el trabajo tengo un Ubuntu Server 10.04 y quise conectarme a el por medio de SSH(para sentirme mas hombre :P ), para esto instale OpenSSH y lo hice de la siguiente manera.

Abrimos la terminal y ponemos los siguiente, que nos instalara el cliente y servidor de openssh:
sudo apt-get install openssh-server openssh-client

Una vez terminado el proceso ya tenemos instalado OpenSSH Server y para probarlo, en terminal ponemos:
ssh localhost

o tambien y asi se usa para conectarse de manera remota:
ssh usuario@ip-de-tu-servidor

Ahora si queremos detener el servicio de ssh, en la terminal ponemos:
sudo /etc/init.d/ssh stop

Para iniciarlo:
sudo /etc/init.d/ssh start

Para reiniciarlo:
sudo /etc/init.d/ssh restart

Enviar Correo con ASP/VB.NET

Si te ves en la necesidad de mandar un correo usando visual basic .net, el siguiente código te va ser de gran ayuda.

Lo primero que hay que hacer en importar la librería a nuestro proyecto Web.
Imports System.Web.Mail

Después el siguiente código lo podemos meter dentro del evento click en el botón “enviar”, mas delante daré un ejemplo practico. Solo hay que remplazar los datos que que nos indica.
Dim correo As New System.Net.Mail.MailMessage()

correo.From = New System.Net.Mail.MailAddress("nombre@delremitente.com")
correo.To.Add("nombre@deldestinatario.com")
correo.Subject = "Aquí el asunto"
correo.Body = "Aquí el texto correspondiente - Guerratopia"
'Estabvlece en TRUE si vas a enviar codigo HTML
correo.IsBodyHtml = True
'Prioridad del Correo Alta, Baja, Normal
correo.Priority = System.Net.Mail.MailPriority.Normal

Dim smtp As New System.Net.Mail.SmtpClient

'---------------------------------------------
' Estos datos debes rellanarlos correctamente
'---------------------------------------------
smtp.Host = "servidor.de.correo_o_Exchange"
'Indicar el puerto en caso de que no sea el Standard (25)
'smtp.Port = "###"
smtp.Credentials = New System.Net.NetworkCredential("usuario", "password")
'Establece en True Cuando el Servidor Requiere una conexion segura
smtp.EnableSsl = False

Try
smtp.Send(correo)
MsgBox("Mensaje enviado satisfactoriamente")
Catch ex As Exception
MsgBox("ERROR: " & ex.Message)
End Try

Aquí puedes descargar un ejemplo practico y sumamente sencillo, solo necesitas poner los datos de las credenciales del servidor de envió y una vez que cambien los datos corran el proyecto (VS2008) y den click en el botón de enviar, verán algo similar a esto en su bandeja de entrada :P