10 dicas úteis e trechos para Apple iPhone e Xcode

1. Cordas de várias linhas

No Xcode, você pode "quebrar" a string em várias linhas, inserindo no final com uma barra invertida "\". Este recurso pode ser útil quando, por exemplo, queremos inserir texto em um controle HTML UIWebView :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
htmlData = @ " \ NSString * HTMLData = @ "\
html head \
<style type= \" text/css \"> \
body {background: # 000; color: # fff} \
</ Style> \
<title> Relatório </ title> </ head> \
<body> \
Tente <h1> HTML </ h1> \
<ul> \
<li> texto HTML </ li> \
Postado em <li> </ li> \
<li> mais linhas '</ li> \
</ Ul> </ body> </ html> ";
htmlData baseURL : [ NSURL URLWithString : @ "http://www.saidmade.com/" ] ] ; [WebView loadHTMLString: HTMLData baseURL: [ NSURL URLWithString: @ "http://www.saidmade.com/"]];

2. Transições entre Ver com efeito de "papel dobrado"

Aqui está um recurso útil para navegar, e risflogliare dois UIView :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/ / Executa um efeito de transição com CURL de um UIView em um UIView
/ / @ Params espaço reservado (UIView) main
/ / @ Params fview (UIView), a partir
/ / @ Params TView (UIView) de chegada
/ / @ Params frente (BOOL) Vá para cima ou para baixo

void ) makeTansitionFromView : ( UIWindow * ) placeholder fromView : ( UIView * ) fview toView : ( UIView * ) tview forward : ( BOOL ) forward { - (Void) makeTansitionFromView: (UIWindow *) espaço reservado fromView: (UIView *) fview toview: (UIView *) TView frente: (BOOL) para a frente {
nil context : NULL ] ; [UIView beginAnimations: contexto nulo: NULL];
1.5 ] ; [UIView setAnimationDuration: 1.5];
forward?UIViewAnimationTransitionCurlUp : UIViewAnimationTransitionCurlDown forView : placeholder cache : YES ] ; [UIView setAnimationTransition: forward UIViewAnimationTransitionCurlUp: UIViewAnimationTransitionCurlDown de vista: cache de espaço reservado: SIM];
; [TView removeFromSuperview];
fview ] ; [Espaço reservado addSubview: fview];
; [Fview removeFromSuperview];
tview ] ; [Espaço reservado addSubview: TView];
; [UIView commitAnimations];
}

Pode ser usado da seguinte forma:

1
2
3
4
/ / Display - folhear para a frente
window fromView : primaView.view toView : secondaView.view forward : YES ] ; [Auto makeTansitionFromView: janela fromView: primaView.view toview: secondaView.view frente: YES];
/ / Ocultar - eu navegar de volta
window fromView : secondaView.view toView : primaView.view forward : NO ] ; [Auto makeTansitionFromView: janela fromView: secondaView.view toview: primaView.view frente: NO];

3. Evitar auto escurecimento do visor

Use com cuidado, caso contrário, o consumo imediato da bateria, esta linha de código permite que você mantenha a nossa aplicação sempre visível, impedindo que o iPhone da Apple entra em "stand-by"

1
.idleTimerDisabled = YES ; [UIApplication sharedApplication] IdleTimerDisabled = YES.;

4. Indicador de atividade da rede

A animação que aparece na barra de status no topo da tela do iPhone da Apple, também pode ser usado para enfatizar em nossas aplicações a atividade da rede:

1
2
3
4
5
6
7
/ / Mostra Indicador de atividade da rede ...
.networkActivityIndicatorVisible = YES ; [UIApplication sharedApplication] NetworkActivityIndicatorVisible = YES.;

/ / Suas operações ...

/ / Esconder Indicador de atividade da rede ...
.networkActivityIndicatorVisible = NO ; [UIApplication sharedApplication] NetworkActivityIndicatorVisible = NO.;

5. Indicador de atividade pessoal

Se você não tem a barra de status, pode vir a calhar para mostrar nossa Indicador de Atividade:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/ / Global em algum lugar ... Édipo em um Delegado (. H)
* Atividade UIActivityIndicatorView;

/ / No loadView ou viewDidLoad inicializar o Indicador de Atividade
UIActivityIndicatorView alloc ] initWithActivityIndicatorStyle : UIActivityIndicatorViewStyleWhite ] ; atividade = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleWhite];
activity ] ; [Self.view addSubview: Atividade];
CGPointMake ( 160 , 240 ) ] ; [Atividade setCenter: CGPointMake (160, 240)];
; [Atividade stopAnimating];

/ / Quando precisamos
void ) someMethod { - (Void) {someMethod
; [Atividade startAnimating];
/ / Para fazer ...
; [Atividade stopAnimating];
}

6. Localização

Com esse trecho que você pode entender que "linguagem" está definido nosso dispositivo:

1
2
3
4
5
6
7
/ / Verificar idioma e localização
defaults = [ NSUserDefaults standardUserDefaults ] ; NSUserDefaults * defaults = [ NSUserDefaults standardUserDefaults];
languages = [ defaults objectForKey : @ "AppleLanguages" ] ; NSArray * linguagens = [defaults objectForKey: @ "AppleLanguages"];
currentLanguage = [ languages objectAtIndex : 0 ] ; NSString * CurrentLanguage = [línguas objectAtIndex: 0];

"Current Locale: %@" , [ [ NSLocale currentLocale ] localeIdentifier ] ) ; NSLog (@ "Locale atual:% @", [[ NSLocale currentLocale] LocaleIdentifier]);
"Current language: %@" , currentLanguage ) ; NSLog (@ "linguagem atual:% @", CurrentLanguage);

7. iPhone ou iPod?

Esta classe é útil para determinar qual dispositivo da Apple está em execução a nossa aplicação. Não só podemos determinar o modelo (iPhone ou iPod Touch), mas também a versão. : Criar dois arquivos UIDevice-hardware.h e UIDevice-hardware.m :

1
2
3
4
5
6
7
8
9
10
11
12
13
/ / UIDevice-hardware.h
# Importar <UIKit/UIKit.h>

# Define IPHONE_1G_NAMESTRING @ "iPhone 1G"
# Define IPHONE_3G_NAMESTRING @ "iPhone 3G"
# Define IPHONE_3GS_NAMESTRING @ "iPhone 3GS"
# Define IPOD_1G_NAMESTRING @ "iPod Touch 1G"
# Define IPOD_2G_NAMESTRING @ "iPod Touch 2G"

Hardware ) @ UIDevice interface (Hardware)
NSString * ) platform; - ( NSString *) plataforma;
NSString * ) platformString; - ( NSString *) platformString;
@ End
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/ / UIDevice-hardware.m
# Import "UIDevice-hardware.h"
# Include <sys/types.h>
# Incluir <sys/sysctl.h>

Hardware ) @ Implementação UIDevice (Hardware)

/ *
Plataformas
iPhone1, 1 = iPhone 1G
iPhone1, 2 = iPhone 3G
iPhone2, 1 = iPhone 3GS
iPod1, 1 = iPod touch 1G
iPod2, 1 = iPod touch 2G
* /

NSString * ) platform { - ( NSString *) {plataforma
size_t tamanho;
, NULL , & size, NULL , 0 ) ; sysctlbyname ("hw.machine", NULL, & size, NULL, 0);
machine = malloc ( size ) ; char * máquina = malloc (tamanho);
, machine, & size, NULL , 0 ) ; ysctlbyname ("hw.machine", a máquina, e tamanho, NULL, 0);
platform = [ NSString stringWithCString : machine ] ; NSString * plataforma = [ NSString stringWithCString: máquina];
machine ) ; livre (máquina);
voltar plataforma;
}

NSString * ) platformString { - ( NSString *) {platformString
platform = [ self platform ] ; NSString * plataforma = [auto-plataforma];
platform isEqualToString : @ "iPhone1,1" ] ) return IPHONE_1G_NAMESTRING; if ([plataforma isEqualToString: @ "iPhone1, um"]) return IPHONE_1G_NAMESTRING;
platform isEqualToString : @ "iPhone1,2" ] ) return IPHONE_3G_NAMESTRING; if ([plataforma isEqualToString: @ "iPhone1, 2"]) return IPHONE_3G_NAMESTRING;
platform isEqualToString : @ "iPhone2,1" ] ) return IPHONE_3GS_NAMESTRING; if ([plataforma isEqualToString: @ "iPhone2, um"]) return IPHONE_3GS_NAMESTRING;
platform isEqualToString : @ "iPod1,1" ] ) return IPOD_1G_NAMESTRING; if ([plataforma isEqualToString: @ "iPod1, um"]) return IPOD_1G_NAMESTRING;
platform isEqualToString : @ "iPod2,1" ] ) return IPOD_2G_NAMESTRING; if ([plataforma isEqualToString: @ "iPod2, um"]) return IPOD_2G_NAMESTRING;
; retornar NULL;
}
@ End

No nosso Delegado pode entrar:

1
2
3
4
5
6
# Import "UIDevice-hardware.h"
/ /
void ) checkDeviceTypeAndCapabilities { - (Void) {checkDeviceTypeAndCapabilities
"type: %@" , [ [ UIDevice currentDevice ] platform ] ) ; NSLog (@ "digite:% @", [[UIDevice currentDevice] plataforma]);
"type: %@" , [ [ UIDevice currentDevice ] platformString ] ) ; NSLog (@ "digite:% @", [[UIDevice currentDevice] platformString]);
}

8. Quarto

Quando você escreve um aplicativo que usa o acesso às funções da Câmara é verificar se o "dispositivo" apoia estas características (tais como as directivas da Apple):

1
2
3
4
5
6
UIImagePickerController * imgPicker;
/ / ...
UIImagePickerController isSourceTypeAvailable : UIImagePickerControllerSourceTypeCamera ] ) ) { if (([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])) {
self.imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
self.imgPicker animated : YES ] ; [Auto presentModalViewController: self.imgPicker animado: YES];
}

9. Photo Album & Photo Library

À semelhança do que acontece com a Câmara, é bom para fazer os controles adequados, mesmo ao acessar a biblioteca de imagens:

1
2
3
4
5
6
7
8
9
10
11
UIImagePickerController * imgPicker;
/ / ...
UIImagePickerController isSourceTypeAvailable : UIImagePickerControllerSourceTypeSavedPhotosAlbum ] ) ) { if (([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeSavedPhotosAlbum])) {
self.imgPicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
self.imgPicker animated : YES ] ; [Auto presentModalViewController: self.imgPicker animado: YES];
}
/ / Ou ...
UIImagePickerController isSourceTypeAvailable : UIImagePickerControllerSourceTypePhotoLibrary ] ) ) { if (([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary])) {
self.imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
self.imgPicker animated : YES ] ; [Auto presentModalViewController: self.imgPicker animado: YES];
}

10. Disponibilidade e tipo de rede

Felizmente, a Apple tem escrito para nós uma classe para determinar o status da rede. Isso pode ser usado em nossa aplicação é verificar se o seu tipo de rede: Ethernet ou Wi-Fi. Baixar Reachability.h e Reachability.m . Adicione o quadro SystemConfiguration.framework . Para isso, você pode escrever uma função como:

1
2
3
4
5
6
7
8
9
10
/ / Em seu Delegado. H
@ Acessibilidade Classe;
/ /
/ / Delegado dentro M
# Import "Reachability.h"

/ / Verifique a cobertura de rede
BOOL ) CheckNetworkStatus { - (BOOL) {CheckNetworkStatus
Reachability reachabilityForInternetConnection ] retain ] != NotReachable ) ; return ([[acessibilidade reachabilityForInternetConnection] reter] = NotReachable!);
}

Por favor, note que o código da Apple, cuja fonte completo pode ser encontrado em Reachability.zip , é para SDK 3.1.2. Se você tentar compilar para SDK 2.2.1 você tem a comentar sobre algumas partes do código que não são suportados pelo "velho" (embora ainda presente) SDK, como o define:

1
2
kSCNetworkReachabilityFlagsConnectionOnTraffic
kSCNetworkReachabilityFlagsConnectionOnDemand

ea parte do código (a comentar):

1
2
3
4
5
6
7
8
9
10
11
12
/ / Se ((((bandeiras e kSCNetworkReachabilityFlagsConnectionOnDemand) = 0)! | |
/ / (Flags & kSCNetworkReachabilityFlagsConnectionOnTraffic)! = 0))
/ / {
/ / / / ... ea conexão é on-demand (ou no tráfego), se o
/ / / / Aplicativo de chamada está usando o CFSocketStream ou superior APIs
/ /
/ / If ((bandeiras e kSCNetworkReachabilityFlagsInterventionRequired) == 0)
/ / {
/ / / / ... e não [usuário] é necessário intervir
/ / RetVal = ReachableViaWiFi;
/ /}
/ /}

Não há comentários para este post

Deixe um comentário

TAG XHTML permita: Código de acesso:
 <pre></pre> // blocco generico <code></code> // blocco generico [cc_actionscript][/cc_actionscript] // Actionscript [cc_actionscript3][/cc_actionscript3] // Actionscript 3 [cc_css][/cc_css] // CSS Style Sheet [cc_html][/cc_html] // HTML [cc_js][/cc_js] // Javascript [cc_objc][/cc_objc] // Objective-C [cc_php][/cc_objc] // PHP [cc_sql][/cc_sql] // SQL