Técnicas Avanzadas de Programación en iOS

Download Report

Transcript Técnicas Avanzadas de Programación en iOS

1
Técnicas Avanzadas de
Programación en iOS
#iOSprogramacion
mobile intelligence Software Engineering Lab
Agenda
2





Presentación del grupo
PayPal
Redes Sociales
Personalización de tablas
Generación de Tiles
Agenda
3





Presentación del grupo
PayPal
Redes Sociales
Personalización de tablas
Generación de Tiles
¿Quiénes somos?
4
¿Qué hacemos?
5



Integración con mapas
Integración con pasarelas de pago
Integración con redes sociales
¿Qué hacemos?
6

Mapas
¿Qué hacemos?
7

Pasarelas de pago
¿Qué hacemos?
8

Redes Sociales
Nosotros
9

José Ángel, Roberto, Adrián y Javier
@Legasquare90
@roberes19
@jshcd
@strikecr
Agenda
10





Presentación del grupo
PayPal
Redes Sociales
Personalización de tablas
Generación de Tiles
PayPal
11




Se puede incluir PayPal en diferentes plataformas
móviles.
Ofrecen una versión Web y otra integra en la
aplicación.
Ofrecen un entorno de pruebas.[1]
Antes de subir la App, ésta deberá pasar una
revisión por parte de PayPal.
PayPal (2)
12





Ofrecen códigos de ejemplo en diferentes
lenguajes. [2]
SDKs para diferentes lenguajes. [3]
Librerías para iOS y Android. [3]
Ofrecen un asistente de integración que genera un código
para la integración de Pago exprés. [4]
Otros asistentes de integración. [5]
PayPal (3)
13
Order2ViewController.m
if (!tokenFetchAttempted) {
tokenFetchAttempted = TRUE;
reviewButton.enabled = FALSE;
//Fetch the device reference token immediately before displaying the page containing
the Pay with PayPal button.
//You might display a UIActivityIndicatorView here to let the user know something is
going on.
[[PayPal getPayPalInst] fetchDeviceReferenceTokenWithAppID:@"APP80W284485P519543T" forEnvironment:ENV_SANDBOX withDelegate:self];
return;
}
reviewButton.enabled = TRUE;
PayPal (4)
14
Order2ViewController.m
NSMutableString *buf = [NSMutableString stringWithString:@"http://paydemo.sms4me.com/ECDemoserver/cart.jsp?"];
[buf appendFormat:@"delivery=%@", delivery.selectedSegmentIndex == 1 ? @"true" : @"false"];
[buf appendFormat:@"&count=%d", pizzaCount.selectedSegmentIndex + 1];
[buf appendString:@"&size="];
switch (size) {
case SIZE_SMALL:
[buf appendString:@"Small"];
break;
case SIZE_MEDIUM:
[buf appendString:@"Medium"];
break;
case SIZE_LARGE:
[buf appendString:@"Large"];
break;
}
PayPal (5)
15
Order2ViewController.m
if (toppingsArray.count > 0) {
[buf appendFormat:@"&toppings=%@", [[toppingsArray objectAtIndex:0]
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
for (int i = 1; i < toppingsArray.count; i++) {
[buf appendFormat:@",%@", [[toppingsArray objectAtIndex:i]
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}
}
if (drt.length > 0) {
[buf appendFormat:@"&drt=%@", drt];
}
PayPal (6)
16
Order2ViewController.m
[self.navigationController pushViewController:[[[WebViewController alloc]
initWithURL:buf endURL:@"http://paydemo.sms4me.com/ECDemo-server/cancel.html"]
autorelease] animated:TRUE];
Agenda
17





Presentación del grupo
PayPal
Redes Sociales
Personalización de tablas
Generación de Tiles
Redes sociales (1/2)
18

3 principales redes sociales en España:
Tuenti: No posee “zona de desarrollo”.
 Facebook: Cantidad de herramientas para desarrollar.



Twitter: Más sencillo, pero contiene todas las funcionalidades.


http://developers.facebook.com
http://dev.twitter.com/
Otras redes sociales
Redes sociales (2/2)
19

2 frameworks para iOS:

Twitter.h
Específico para Twitter y para iOS.
 Problemas a partir de iOS 6.1


Social.h
Combina mayor número de redes sociales: Twitter, Facebook y
Sina Weibo.
 Muy similar a Twitter.h

Enviar un mensaje en Twitter
20
Order2ViewController.h
#import <Social/Social.h>
…
-(IBAction)twittear:(id)sender;
Order2ViewController.m
SLComposeViewController *tw = [SLComposeViewController
composeViewControllerForServiceType:SLServiceTypeTwitter];
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter]) {
[tw setInitialText:mensaje];
[self presentModalViewController:tw animated:YES];
}
Cargar vista de Timeline
21
TwitterViewController.h
#import <Social/Social.h>
#import <Accounts/Accounts.h>
TwitterViewController.m
HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
[self.navigationController.view addSubview:HUD];
HUD.delegate = self;
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
[self cargarTweets];
Timeline de Twitter (1/4)
22
TwitterViewController.m
NSURL *url = [NSURL URLWithString:@"http://api.twitter.com/1.1/search/tweets.json"];
NSString *terminoBusqueda = @"#PizzaExpress #iOSprogramacion";
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore
accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType
withCompletionHandler:^(BOOL granted, NSError *error) {
if (granted) {
NSArray *accounts = [accountStore accountsWithAccountType:accountType];
if (accounts.count) {
ACAccount *twitterAccount = [accounts objectAtIndex:0];
//Obtener datos
}
}
}];
Timeline de Twitter (2/4)
23
TwitterViewController.m
//Obtener datos
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
[parameters setObject:terminoBusqueda forKey:@"q"]; //Busqueda
[parameters setObject:@"50" forKey:@"count"];
[parameters setObject:@"0" forKey:@"include_entities"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodGET URL:url parameters:parameters];
[request setAccount:twitterAccount];
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse
*urlResponse, NSError *error) {
if (responseData) {
//Tratar datos
}
}];
Timeline de Twitter (3/4)
24
TwitterViewController.m
//Tratar datos
NSError *error = nil;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData
options:NSJSONReadingMutableLeaves error:&error];
if (dict) {
NSMutableArray *dataSource = [dict mutableArrayValueForKey:@"statuses"];
for (int i=0; i<dataSource.count; i++){
NSDictionary *tweet = dataSource[i];
[names addObject:[[tweet objectForKey:@"user"] objectForKey:@"name"]];
[messages addObject:[tweet objectForKey:@"text"]];
NSURL *imageURL = [NSURL URLWithString:[[tweet objectForKey:@"user"]
objectForKey:@"profile_image_url"]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
[photos addObject:[UIImage imageWithData:imageData]];
}
}
//Recargar datos
Timeline de Twitter (4/4)
25
TwitterViewController.m
[MBProgressHUD hideHUDForView:self.view animated:YES];
[HUD removeFromSuperview];
[HUD release];
HUD = nil;
[tweets reloadData];
cell.textLabel.text = names [indexPath.row];
cell.detailTextLabel.font = [UIFont fontWithName:@"Helvetica" size:12.0];
cell.detailTextLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.detailTextLabel.numberOfLines = 4;
cell.detailTextLabel.text = messages [indexPath.row];
cell.imageView.image = photos [indexPath.row];
Agenda
26





Presentación del grupo
PayPal
Redes Sociales
Personalización de tablas
Generación de Tiles
Personalización de tablas (1/14)
27


Clase -> UITableViewController
Protocolos -> UITableViewDataSource
 Modelo <- - -> Vista
-> UITableViewDelegate
 Comportamiento y Apariencia de la
vista
Personalización de tablas (2/14)
28
ListaLugaresViewController.h
@interface ListaLocalesViewController : UIViewController<UITableViewDataSource,
UITableViewDelegate>{
IBOutlet UITableView *tablaLocales;
NSMutableArray *listadoLocales;
NSMutableArray *listadoDirecciones;
}
Personalización de tablas (3/14)
29

Tipos de tablas
Plain
Grouped
Personalización de tablas (4/14)
30
ListaLugaresViewController.m -> Personalización de encabezados de sección
// Personalizar el encabezado de cada seccion
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
}
Personalización de tablas (5/14)
31
ListaLugaresViewController.m -> Personalización de encabezados de sección
// Crea la vista de cada seccion
CGRect referenceRect = CGRectMake(0, 0, tableView.bounds.size.width, 25);
UIView *headerView = [[UIView alloc] initWithFrame:referenceRect];
[headerView setBackgroundColor:[[UIColor colorWithRed:6.0/255.0 green:24.0/255.0
blue:188.0/255.0 alpha:1.0] initWithHue:0.0 saturation:0.0 brightness:1.0 alpha:1.0]];
headerView.opaque = NO;
Personalización de tablas (6/14)
32
ListaLugaresViewController.m -> Personalización de encabezados de sección
// Crea el contenido de la vista
UILabel *sectionTitle = [[UILabel alloc] initWithFrame:referenceRect];
[sectionTitle setBackgroundColor:[UIColor colorWithRed:6.0/255.0 green:24.0/255.0
blue:188.0/255.0 alpha:1.0]];
sectionTitle.opaque = NO;
sectionTitle.textColor = [UIColor whiteColor];
sectionTitle.text = @" Locales Cercanos";
// Añade el contenido a la vista
[headerView addSubview:sectionTitle];
return headerView;
Personalización de tablas (7/14)
33
ListaLugaresViewController.m -> DisclosureButton
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
[cell.imageView initWithFrame:CGRectMake(0, 0, 54, 72)];
}
Personalización de tablas (8/14)
34
ListaLugaresViewController.m -> Imagen en una celda
// Imagen del local
UIImage *logoLocal;
NSString *nombreLogoLocal;
switch (indexPath.row) {
case 0:
nombreLogoLocal = @"dicarlo.png";
break;
case 1:
nombreLogoLocal = @"telepizza.png";
break;
Personalización de tablas (9/14)
35
ListaLugaresViewController.m -> Imagen en una celda
case 3:
nombreLogoLocal = @"pizzitas.png";
break;
case 4:
nombreLogoLocal = @"cafeteriaPequeña.png";
break;
default:
break;
}
Personalización de tablas (10/14)
36
ListaLugaresViewController.m -> Imagen en una celda
logoLocal = [UIImage imageNamed:nombreLogoLocal];
UIImage *iconoLogoLocal = [UIImage imageWithCGImage:[logoLocal CGImage] scale:0
orientation:0];
cell.imageView.image = iconoLogoLocal;
Personalización de tablas (11/14)
37
ListaLugaresViewController.m -> Alto de fila
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath
*)indexPath
{
return tableView.rowHeight + 40;
}
Personalización de tablas (12/14)
38
ListaLugaresViewController.m -> Acción a realizar en tap sobre disclosure button
- (void)tableView:(UITableView *)tableView
accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
NSString *appURL = @"http://maps.google.com/maps?q=";
appURL = [appURL stringByAppendingFormat:[self.listadoDirecciones
objectAtIndex:indexPath.row]];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[self openInSafari:appURL];
}
Personalización de tablas (13/14)
39



URL Scheme -> permite lanzar una app desde otra
app
Hay que definir un scheme en la app que se va a
lanzar
La app que se va a lanzar captura el Scheme y
realiza las acciones convenientes:
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL
*)url
Personalización de tablas (14/14)
40
ListaLugaresViewController.m -> Uso de URL Scheme
NSString *appURL = @"uc3mmapas://place/1/";
appURL = [appURL stringByAppendingFormat:[self.listadoDirecciones
objectAtIndex:indexPath.row]];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[self openInSafari:appURL];
Agenda
41





Presentación del grupo
PayPal
Redes Sociales
Personalización de tablas
Generación de Tiles
Generación de tiles (1/4)
42

¿Qué son los tiles?
 (del
inglés) azulejos.
 cada una de las imágenes que conforman un plano
estándar como los de Google Maps, Yahoo Maps,
Microsoft VirtualEarth u OpenStreeMap.

¿Cómo se generan?
 Editor
gráfico (p.e. Photoshop).
 GDAL - Geospatial Data Abstraction Library.
 MapTiler (versión BETA que no funciona
ni en Mac OSX Lion ni Mountain Lion).
Generación de tiles (2/4)
43

Editor gráfico
 Utilizamos
alguno en el que se puedan utilizar capas y
dibujamos la imagen que queramos superponer.
 Exportamos cada capa a un fichero TIFF diferente.
Generación de tiles (3/4)
44

Convertimos los ficheros TIFF a formato VRT con
GDAL
 Es
el paso intermedio antes de general los tiles con
MapTiler.
 Se necesitan al menos 3 puntos (recomendable 4).
gdal_translate -of VRT -a_srs EPSG:4326 -gcp 8 536 -3.795605 40.312847 -gcp 128
52 -3.785466 40.34441 -gcp 635 10 -3.741574 40.347272 -gcp 452 484 -3.75741
40.316185 zona2.tif zona2.vrt
 En
naranja, las coordenadas en pixeles y en azul, las
coordenadas geoespaciales. En rojo el fichero de
entrada y en verde el fichero de salida.
Generación de tiles (4/4)
45

Generación automática de los tiles
 Seleccionamos
el tipo de conversión que queremos
realizar.
 Seleccionamos los niveles de zoom que queremos
generar para mostrar en nuestra app.
Bibliografía
46
[1]https://cms.paypal.com/es/cgi-bin/?cmd=_rendercontent&content_ID=developer/howto_testing_sandbox
[2]https://cms.paypal.com/es/cgi-bin/?cmd=_rendercontent&content_ID=developer/library_code
[3]https://www.x.com/developers/paypal/documentationtools/paypal-sdk-index
[4] https://www.paypallabs.com/integrationwizard/ecpaypal/main.php
[5] https://www.paypal-labs.com/integrationwizard/index.php
47
Técnicas Avanzadas de
Programación en iOS
#iOSprogramacion
mobile intelligence Software Engineering Lab