10 astuces utiles et des extraits pour Apple iPhone et Xcode

1. Chaînes sur plusieurs lignes

Dans Xcode, vous pouvez "casser" une chaîne sur plusieurs lignes en insérant à la fin avec une barre oblique inverse "\". Cette fonctionnalité peut être utile lorsque, par exemple, nous voulons insérer le texte HTML dans un contrôle 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> \
Signaler <title> </ title> </ head> \
<body> \
Essayez <h1> HTML </ h1> \
<ul> \
<li> Texte HTML </ li> \
Posté le <li> </ li> \
lignes »<li> plus </ li> \
</ Ul> </ body> </ html> ";
htmlData baseURL : [ NSURL URLWithString : @ "http://www.saidmade.com/" ] ] ; [WebView loadHTMLString: htmlData baseURL: [ NSURL URLWithString: @ "http://www.saidmade.com/"]];

2. Les transitions entre View avec effet "pliées"

Voici une fonctionnalité très utile pour naviguer et risflogliare, deux UIView :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/ / Effectue une transition avec effet à partir CURL à un UIView UIView
/ / @ Params espace réservé (UIView) principale
/ / @ Params fview (UIView) de départ
/ / @ Params tview (UIView) l'arrivée
/ / @ Params avant (BOOL) Parcourir haut ou le bas

void ) makeTansitionFromView : ( UIWindow * ) placeholder fromView : ( UIView * ) fview toView : ( UIView * ) tview forward : ( BOOL ) forward { - (Void) makeTansitionFromView: (UIWindow *) placeholder fromView: (UIView *) fview toView: (UIView *) tview avant: (BOOL) {avant
nil context : NULL ] ; [BeginAnimations UIView: contexte nul: NULL];
1.5 ] ; [UIView setAnimationDuration: 1,5];
forward?UIViewAnimationTransitionCurlUp : UIViewAnimationTransitionCurlDown forView : placeholder cache : YES ] ; [UIView setAnimationTransition: avant UIViewAnimationTransitionCurlUp: UIViewAnimationTransitionCurlDown forView: cache d'espace réservé: OUI];
; [Tview removeFromSuperview];
fview ] ; [Placeholder addSubview: fview];
; [Fview removeFromSuperview];
tview ] ; [Placeholder addSubview: tview];
; [CommitAnimations UIView];
}

Il peut être utilisé de cette manière:

1
2
3
4
/ / Affichage - Faire défiler en avant
window fromView : primaView.view toView : secondaView.view forward : YES ] ; [Self makeTansitionFromView: fenêtre fromView: primaView.view toView: secondaView.view avant: YES];
/ / Cacher - feuilletez retour
window fromView : secondaView.view toView : primaView.view forward : NO ] ; [Self makeTansitionFromView: fenêtre fromView: secondaView.view toView: primaView.view avant: NO];

3. Empêcher atténuation automatique de l'écran

Pour être utilisé avec précaution, sous peine de la consommation immédiate de la batterie, cette ligne de code permet de garder notre application toujours visible, ce qui empêche l'iPhone d'Apple passe en "standby"

1
.idleTimerDisabled = YES ; [SharedApplication UIApplication] IdleTimerDisabled = OUI.;

4. Indicateur d'activité réseau

L'animation qui apparaît sur la barre d'état en haut de l'écran de l'iPhone d'Apple, peut également être utilisé pour mettre en évidence une application de notre réseau:

1
2
3
4
5
6
7
/ Indicateur / Afficher l'activité du réseau ...
.networkActivityIndicatorVisible = YES ; [SharedApplication UIApplication] NetworkActivityIndicatorVisible = OUI.;

/ / Vos opérations ...

/ / Cacher indicateur d'activité réseau ...
.networkActivityIndicatorVisible = NO ; [SharedApplication UIApplication] NetworkActivityIndicatorVisible = NO.;

5. Indicateur d'activité personnelle

Si vous n'avez pas la barre d'état, peut être utile de montrer l'un de nos indicateurs d'activité:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/ / Global quelque part ... Œdipe dans un Délégué (. H)
* L'activité UIActivityIndicatorView;

/ / Initialisation de la viewDidLoad En loadview ou Indicateur d'activité
UIActivityIndicatorView alloc ] initWithActivityIndicatorStyle : UIActivityIndicatorViewStyleWhite ] ; l'activité = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleWhite];
activity ] ; [Self.view addSubview: activité];
CGPointMake ( 160 , 240 ) ] ; [Activité SetCenter: CGPointMake (160, 240)];
; [Activité StopAnimating];

/ / Quand nous avons besoin
void ) someMethod { - (Void) {someMethod
; [Activité StartAnimating];
/ / Pour faire ...
; [Activité StopAnimating];
}

6. Lieu

Avec cet extrait vous pouvez comprendre que le «langage» est notre devise:

1
2
3
4
5
6
7
/ / Vérification de la langue et la localisation
defaults = [ NSUserDefaults standardUserDefaults ] ; NSUserDefaults * par défaut = [ NSUserDefaults standardUserDefaults];
languages = [ defaults objectForKey : @ "AppleLanguages" ] ; NSArray * langues = [défaut objectForKey: @ "francais.applelanguages ​​Nos"];
currentLanguage = [ languages objectAtIndex : 0 ] ; NSString * currentLanguage = [langues objectAtIndex: 0];

"Current Locale: %@" , [ [ NSLocale currentLocale ] localeIdentifier ] ) ; NSLog (@ "locale courante:% @", [[ NSLocale currentLocale] LocaleIdentifier]);
"Current language: %@" , currentLanguage ) ; NSLog (@ "langage courant:% @", currentLanguage);

7. iPhone ou iPod?

Cette classe est utile pour déterminer quel appareil Apple est en marche notre application. Non seulement nous pouvons déterminer le modèle (iPhone ou iPod Touch) mais aussi la version. : Créer deux fichiers UIDevice-hardware.h et UIDevice-hardware.m :

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

@ # Définir IPHONE_1G_NAMESTRING "iPhone 1G"
@ # Définir IPHONE_3G_NAMESTRING "iPhone 3G"
@ # Définir IPHONE_3GS_NAMESTRING "iPhone 3G"
@ # Définir IPOD_1G_NAMESTRING "iPod touch 1G"
@ # Définir IPOD_2G_NAMESTRING "iPod Touch 2G"

Hardware ) @ Interface UIDevice (Hardware)
NSString * ) platform; - ( NSString *) plate-forme;
NSString * ) platformString; - ( NSString *) platformString;
@ Fin
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
# Inclure <sys/sysctl.h>

Hardware ) @ Mise en oeuvre UIDevice (Hardware)

/ *
Plates-formes
iPhone1, 1 = 1G iPhone
iPhone1, 2 iPhone 3G =
iPhone2, 1 iPhone 3G =
iPod1, 1 = iPod touch 1G
iPod2, 1 = iPod touch 2G
* /

NSString * ) platform { - ( NSString *) {plateforme
size_t size;
, NULL , & size, NULL , 0 ) ; sysctlbyname ("hw.machine", NULL, & taille, NULL, 0);
machine = malloc ( size ) ; char * machine = malloc (taille);
, machine, & size, NULL , 0 ) ; ysctlbyname ("hw.machine", des machines, & taille, NULL, 0);
platform = [ NSString stringWithCString : machine ] ; NSString * plateforme = [ NSString stringWithCString: machine];
machine ) ; libre (machines);
retour plate-forme;
}

NSString * ) platformString { - ( NSString *) {platformString
platform = [ self platform ] ; NSString * plateforme = [plate-forme auto];
platform isEqualToString : @ "iPhone1,1" ] ) return IPHONE_1G_NAMESTRING; if ([plate-forme isEqualToString: @ "iPhone1, 1"]) return IPHONE_1G_NAMESTRING;
platform isEqualToString : @ "iPhone1,2" ] ) return IPHONE_3G_NAMESTRING; if ([plate-forme isEqualToString: @ "iPhone1, 2"]) return IPHONE_3G_NAMESTRING;
platform isEqualToString : @ "iPhone2,1" ] ) return IPHONE_3GS_NAMESTRING; if ([plate-forme isEqualToString: @ "iPhone2, 1"]) return IPHONE_3GS_NAMESTRING;
platform isEqualToString : @ "iPod1,1" ] ) return IPOD_1G_NAMESTRING; if ([plate-forme isEqualToString: @ "iPod1, 1"]) return IPOD_1G_NAMESTRING;
platform isEqualToString : @ "iPod2,1" ] ) return IPOD_2G_NAMESTRING; if ([plate-forme isEqualToString: @ "iPod2, 1"]) return IPOD_2G_NAMESTRING;
; return null;
}
@ Fin

Dans notre délégation à entrer:

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

8. Chambre

Lorsque vous écrivez une application qui utilise l'accès aux fonctions de la Chambre est de vérifier que le "dispositif" prend en charge ces fonctionnalités (conformément aux directives d'Apple):

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

9. Albums photo & Photo Library

Similaire à ce qui se passe avec la Chambre, il est préférable de simplement vérifier lorsque vous accédez à la bibliothèque d'images:

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 ] ; [PresentModalViewController Auto: self.imgPicker animé: YES];
}
/ / Ou ...
UIImagePickerController isSourceTypeAvailable : UIImagePickerControllerSourceTypePhotoLibrary ] ) ) { if (([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary])) {
self.imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
self.imgPicker animated : YES ] ; [PresentModalViewController Auto: self.imgPicker animé: YES];
}

10. Disponibilité et type de réseau

Heureusement, Apple a écrit une classe pour nous de déterminer l'état du réseau. Ceci peut être utilisé dans notre application est de vérifier que votre topologie de réseau: Ethernet ou WiFi. Télécharger Reachability.h et Reachability.m . Ajouter le Cadre SystemConfiguration.framework . Ici vous pouvez écrire une fonction comme:

1
2
3
4
5
6
7
8
9
10
/ / Dans votre délégué. H
Accessibilité @ classe;
/ /
/ / Les délégués po M
# Import "Reachability.h"

/ / Vérifier la couverture du réseau
BOOL ) CheckNetworkStatus { - (BOOL) {CheckNetworkStatus
Reachability reachabilityForInternetConnection ] retain ] != NotReachable ) ; retour ([reachabilityForInternetConnection atteignabilité [] retain] = NotReachable!);
}

S'il vous plaît noter que le code d'Apple, qui est disponible en code source complet Reachability.zip est pour le SDK 3.1.2. Si vous essayez de remplir pour SDK 2.2.1, vous devez faire des commentaires sur quelques morceaux de code ne sont pas pris en charge par les «anciens» (même si elles existent encore) SDK, tels que définir:

1
2
kSCNetworkReachabilityFlagsConnectionOnTraffic
kSCNetworkReachabilityFlagsConnectionOnDemand

et le morceau de code (pour un commentaire):

1
2
3
4
5
6
7
8
9
10
11
12
/ / Si ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand) = 0)! | |
/ / (Drapeaux & kSCNetworkReachabilityFlagsConnectionOnTraffic)! = 0))
/ / {
/ / / / ... et la connexion est à la demande (ou sur la circulation) si le
/ / / / Application appelante utilise les API ou plus CFSocketStream
/ /
/ / If ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
/ / {
/ / / / ... et aucune intervention [utilisateur] est nécessaire
/ / Retval = ReachableViaWiFi;
/ /}
/ /}

Il n'y a aucun commentaire pour cet article

Laisser un commentaire

XHTML TAG PERMIS: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> CODE D'INSERTION:
 <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 


Arrêtez SOPA