che in modalità POST . The object NSMutableURLRequest can be used in either GET mode in POST . . The parameters, however, must be formatted as if they were in GET , ie in the sequence nome_campo1=valore1&nome_campo2=valore2&... . Here's a useful snippet to simplify the construction of fields:
Articles Tagged 'NSString'
Very short snippet: NSConnection POST with parameters
10 useful snippets Objective-C
Move the double-tap on the simulator
The simulator iPhones / iPad Xcode allows you to simulate the double tap the Alt key is pressed. This is useful to simulate the function of Pinch, that used to enlarge or scroll Keep away content in the view with objects or UIWebView . Well, some of you have noticed that the simulation of the "two fingers" proceeds in a symmetrical manner always starting from the center of the screen. To move this "center" is also just hold down the SHIFT key.
How to develop in PHP with Xcode and Objective-C
How many programmers to use, I also build my own library of functions ready to be reused in multiple projects and multiple contexts. Let me change the title of this post, maybe a little 'risky but, nevertheless, as we shall see, not far from reality.
In Objective-C you can write and call C / C + +, including the assembly for that matter. This characteristic makes it a very versatile language and, in some respects, phenomenal. On the one hand, you can use and appreciate the purely syntax of Objective-C, on the other you can run faster porting code written in ANSI C (perhaps for Digital Unix or Sun) and can comfortably fit into our iPhone or iPad applications; not to mention all the BSD kernel is already available on Mac OS X!
Very short snippet: NSURL, and various possible
Returns the name of a file from the object NSURLRequest , allowing you to decide whether or not its extension:
NSString
NSString is a powerful class, let me show you some of the most used properties:
printf ()
1 2 |
Run the split ()
1 2 3 |
Convert from string to value
1 2 3 | / / Converting doubleString = @ "123" ; NSString * @ doubleString = "123"; [ doubleString doubleValue ] ; double value = [doubleString doubleValue]; |
Within a string
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | / / Substring searchString = @ "age" ; NSString * @ searchString = 'age'; beginsTest = @ "Agencies" ; NSString * beginsTest @ = "Agencies"; [ beginsTest rangeOfString : searchString NSRange prefixRange = [beginsTest rangeOfString: searchString NSAnchoredSearch | NSCaseInsensitiveSearch ) ] ; options: (NSAnchoredSearch | NSCaseInsensitiveSearch)]; / / PrefixRange = {0, 3} endsTest = @ "BRICOLAGE" ; NSString * endsTest = @ "DIY"; [ endsTest rangeOfString : searchString NSRange suffixRange = [endsTest rangeOfString: searchString NSAnchoredSearch | NSCaseInsensitiveSearch | NSBackwardsSearch ) ] ; options: (NSAnchoredSearch | NSCaseInsensitiveSearch | NSBackwardsSearch)]; / / SuffixRange = {6, 3} |
How to get Latitude and Longitude in Objective-C
The framework provides MapKit many useful features, except the return of Longitude and Latitude from an address. In JavaScript, for example, you can use the service provided by Google Geocoding and discussed in Google Maps: How to get Latitude and Longitude from an address . Apple iPhone or iPad, however, you can overcome this obstacle by using a different Google services. Specifically, you can call directly to the url:
1 | http://maps.google.com/maps/geo?q = [address] & output = csv |
Where is [indirizzo] to enter the string with the address you want to transform coordinates. The output returned is of type:
1 | 200,8,41.9128300,12.2241172 |
). The first value, 200 , indicates that everything went well ( 200 OK ). The second, 8 , Google is the accuracy parameter (1-10). The last two values are, finally, latitude and longitude. Now we see a prototype of a method can be included in our applications:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | CLLocationCoordinate2D ) getLocationFromAddress : ( NSString * ) address { - (CLLocationCoordinate2D) getLocationFromAddress: ( NSString *) address { urlString = [ NSString stringWithFormat : @ "http://maps.google.com/maps/geo?q=%@&output=csv" , NSString * urlString = [ NSString stringWithFormat: @ "% @ http://maps.google.com/maps/geo?q = & output = csv" NSUTF8StringEncoding ] ] ; [StringByAddingPercentEscapesUsingEncoding address: NSUTF8StringEncoding]]; listItems = [ locationString componentsSeparatedByString : @ "," ] ; NSArray * ListItems = [locationString componentsSeparatedByString: @ ""]; / / Int zoom = 0; 0.0 ; double latitude = 0.0; 0.0 ; double longitude = 0.0; listItems count ] > = 4 && [ [ listItems objectAtIndex : 0 ] isEqualToString : @ "200" ] ) { if ([ListItems count]> = 4 & & [[ListItems objectAtIndex: 0] isEqualToString: @ "200"]) { / / Zoom = [[ListItems objectAtIndex: 1] intValue]; listItems objectAtIndex : 2 ] doubleValue ] ; Latitude = [[ListItems objectAtIndex: 2] doubleValue]; listItems objectAtIndex : 3 ] doubleValue ] ; longitude = [[ListItems objectAtIndex: 3] doubleValue]; { Else {} / / Error } CLLocationCoordinate2D location; location.latitude = latitude; location.longitude = longitude; return location; } |
Notes of interest
, alla stregua della funzione explode ( ) del PHP per intenderci. The string returned in locationString is "split" by the method componentsSeparatedByString , like the function explode ( ) in PHP for instance. I put the example I proposed - but commented - the code to retrieve even the Google accuracy parameter, precision or scale factor, denoted by zoom .
Source as
For completeness, I made a small example application with which you can try the method proposed above, enter any address and the iPhone will show on the map.
I thank the team devAPP for the inspiration of this article.
Very short snippet: get the output of a URL in Objective-C
Perhaps I should write "Very very very, short snippets", however, is an excellent and convenient "trick" to show what I am. Running the "two" lines of code shown below, you can get the output of any URL and manipulate it.
Objective-C: NSLog () of C struct
o CGPoint , ad esempio. The syntax NSLog(@"%@", ... ); works and is used to obtain information about objects, but does not work on C data types such as struct CGRect or CGPoint , for example. o NSStringFromCGPoint : To take advantage of NSLog(@"%@", ... ); even on C-style structs can rely on conversion functions like NSStringFromCGRect() or NSStringFromCGPoint :
1 2 3 4 5 | CGRect ) { 10 , 20 , 30 , 40 } ; CGRect mioRect = (CGRect) {10, 20, 30, 40}; CGPoint ) { 32 , 64 } ; CGPoint mioPoint = (CGPoint) {32, 64}; / / "Info rettangolo: %@" , NSStringFromCGRect ( mioRect ) ) ; NSLog (@ "Info rectangle:% @", NSStringFromCGRect (mioRect)); "Info point: %@" , NSStringFromCGPoint ( mioPoint ) ) ; NSLog (@ "Info point:% @", NSStringFromCGPoint (mioPoint)); |
Specifically, it is possible to improve this procedure writes of small useful macros like:
1 | # Define NSLogRect (rect) NSLog (@ "% s (% 0.0f,% 0.0f)% 0.0f% 0.0fx", # rect, rect.origin.x, rect.origin.y, rect.size.width , rect.size.height) |
Or:
1 2 3 4 | # Define NSLogCGPoint (point) NSLog (@ "% s (% 0.0f,% 0.0f)", # point.x point, Point.y) CGPoint ) { 32 , 64 } ; CGPoint mioPoint = (CGPoint) {32, 64}; ; NSLogCGPoint (mioPoint); |
That will give as output:
1 | 32 , 64 ) mioPoint: (32, 64) |
iPhone SecondApp: Guess the number - Part 2
As mentioned FirstApp iPhone: Guess the number - Part 1 we see how to make an application for the Apple iPhone without using Interface Builder! Indeed, we will eliminate physical files created by Interface Builder, Xcode wizard. At the end of this post, then, we have an application identical in all respects, to that achieved in the first part, with the difference that we will achieve all our visual components, including the main Window, completely to code.
The application already made, if you just want to download, is available on my Google Code repository:
I would like to point out immediately as the ZIP of this example weighing less than the last time! ![]()
We create the project
We start by creating our project SecondApp (to distinguish it from FirstApp), although this time choose Window-based Application:

Now let's delete everything related to Interface Builder. : eliminatelo anche dal file system, quindi selezionate Also Move to Trash . Delete the file MainWindow.xib , located in the folder Resources : also delete it from the file system, then select Also Move to Trash. nella casella Main nib file base name : Select then the file SecondoApp-info.plist and delete the reference to the MainWindow nib box Main base file name:

At this point we no longer have any Windows, at least through Interface Builder. , e modifichiamo la funzione main() in questo modo: So we open the file main.m , situated in Other Sources , and modify the function main() like this:
1 2 3 4 5 6 7 8 9 10 11 | int argc, char * argv [ ] ) { int main (int argc, char * argv []) { pool = [ [ NSAutoreleasePool alloc ] init ] ; NSAutoreleasePool * pool = [[ NSAutoreleasePool alloc] init]; / / By removing the file. XIB we missed the point / / Delegate to the JPA, then pass it to "hand" UIApplicationMain ( argc, argv, nil , @ "SecondAppAppDelegate" ) ; int retVal = UIApplicationMain (argc, argv, nil, @ "SecondAppAppDelegate"); ; [Pool release]; return retVal; } |
Open SecondAppAppDelegate.me then create the main Window in code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | void ) applicationDidFinishLaunching : ( UIApplication * ) application { - (Void) applicationDidFinishLaunching: (UIApplication *) application { / / Get the screen size (320, 480) UIScreen mainScreen ] applicationFrame ] ; CGRect windowRect = [[UIScreen Mainscreen] applicationFrame]; / / Create a window - as we have done in Interface Builder bye bye [ [ UIWindow alloc ] initWithFrame : windowRect ] ; MainWindow UIWindow * = [[UIWindow alloc] initWithFrame: windowRect]; / / Set the background of the Window to yellow, to differentiate / / The previous application FirstApp [ UIColor yellowColor ] ] ; [MainWindow setBackgroundColor: [UIColor yellowColor]]; mainWindow ] ; [Self setWindow: mainWindow]; ; [Window makeKeyAndVisible]; ; [MainWindow release]; } |
You can already test the application, if you get a yellow window you did everything right!
, necessario solo se si usa Interface Builder. In the file SecondAppAppDelegate.h we can eliminate IBOutlet , only needed if you use Interface Builder. Also add here that our global variables, the last time we had entered in the Controller. Then modify the file SecondAppAppDelegate.h :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | # Import <UIKit/UIKit.h> NSObject <UIApplicationDelegate> { @ Interface SecondAppAppDelegate: NSObject {<UIApplicationDelegate> UIWindow * window; UITextField * number; UIButton * button; numeroACaso int; } nonatomic, retain ) UIWindow * window; @ Property (nonatomic, retain) UIWindow * window; void ) controllaNumero; - (Void) getNumber; @ End |
, in quanto non stiamo usando Interface Builder. Again we have prepared the method definition controllaNumero , like last time, but we have eliminated the indication IBAction , because you are not using Interface Builder.
We build the interface from code
It 'time to create code using all components of our interface. ed inseriamo il seguente codice: Let's go back to the file SecondAppAppDelegate.m , posizioniamoci before [mainWindow release] and insert the following code:
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 | / / Create the title bar [ [ UINavigationBar alloc ] initWithFrame : CGRectMake ( 0.0 , 0.0 , 320.0 , 44.0 ) ] ; UINavigationBar myNavigationBar * = [[UINavigationBar alloc] initWithFrame: CGRectMake (0.0, 0.0, 320.0, 44.0)]; myNavigationBar.barStyle = UIBarStyleDefault; [ [ UINavigationItem alloc ] initWithTitle : @ "Indovina un numero" ] ; UINavigationItem navigationItem * = [[UINavigationItem alloc] initWithTitle: @ "Guess a number"]; navigationItem animated : NO ] ; [MyNavigationBar pushNavigationItem: navigationItem animated: NO]; myNavigationBar ] ; [Window addSubview: myNavigationBar]; / / Create the label [ [ UILabel alloc ] initWithFrame : CGRectMake ( 10 , 50 , 300 , 80 ) ] ; UILabel myLabel * = [[UILabel alloc] initWithFrame: CGRectMake (10, 50, 300, 80)]; UIColor clearColor ] ; myLabel.backgroundColor = [UIColor clearColor]; ; myLabel.numberOfLines = 2; "iPhone ha pensato un numero da 1 a 10, prova ad indovinarlo?" ; myLabel.text = @ "iPhone has designed a number from 1 to 10, try to guess?" myLabel ] ; [Window addSubview: myLabel]; / / Create text input UITextField alloc ] initWithFrame : CGRectMake ( 10 , 120 , 300 , 30 ) ] ; number = [[UITextField alloc] initWithFrame: CGRectMake (10, 120, 300, 30)]; numero.borderStyle = UITextBorderStyleRoundedRect; numero.textAlignment = UITextAlignmentCenter; numero.keyboardType = UIKeyboardTypeNumberPad; "Inserisci il numero" ; numero.placeholder = @ "Enter the number"; numero ] ; [Window addSubview: number]; / / Create the button UIButton buttonWithType : UIButtonTypeRoundedRect ] ; button = [UIButton buttonWithType: UIButtonTypeRoundedRect]; 10 , 180 , 300 , 30 ) ; bottone.frame = CGRectMake (10, 180, 300, 30); @ "Premi qui" forState : UIControlStateNormal ] ; [Button setTitle: @ "Click Here" Forst: UIControlStateNormal]; self action : @selector ( controllaNumero ) forControlEvents : UIControlEventTouchUpInside ] ; [AddTarget button: self action: @ selector (getNumber) forControlEvents: UIControlEventTouchUpInside]; bottone ] ; [Window addSubview: button]; ; [MyLabel release]; ; [NavigationItem release]; ; [MyNavigationBar release]; |
della scorsa volta, subito dopo il [mainWindow release]; inseriamo: Since the ' applicationDidFinishLaunching corresponds to viewDidLoad as last time, just after the [mainWindow release]; insert:
1 | + arc4random ( ) % 10 ; numeroACaso arc4random = 1 + () 10%; |
Now we can do is implement the method controllaNumero , which will be identical (apart from the prototype) to that used last time:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | void ) controllaNumero { - (Void) {getNumber "Premuto bottone di controlla numero" ) ; NSLog (@ "Pressed button control number"); [ numero.text integerValue ] ; numeroInserito = int [numero.text integerValue]; message; NSString * message; "Il numero inserito è %d" , numeroInserito ) ; NSLog (@ "The number entered is% d", numeroInserito); numeroInserito <numeroACaso ) { if (numeroInserito <numeroACaso) { "Troppo basso..." ; message = @ "Too low ..."; ( numeroInserito> numeroACaso ) { } Else if (numeroInserito> numeroACaso) { "Troppo alto..." ; message = @ "Too high ..."; ( numeroInserito == numeroACaso ) { } Else if (numeroInserito numeroACaso ==) { "Bravo hai indovinato" ; message = @ "Bravo, you guessed it"; + arc4random ( ) % 10 ; numeroACaso arc4random = 1 + () 10%; "Numero pensato %d" , numeroACaso ) ; NSLog (@ "Number% d thought," numeroACaso); } [ [ UIAlertView alloc ] UIAlertView alertMessaggio * = [[UIAlertView alloc] "Responso" initWithTitle: @ "Response" message: message delegate: nil "OK" cancelButtonTitle: @ "OK" ] ; otherButtonTitles: nil]; ; [AlertMessaggio show]; ; [AlertMessaggio release]; "" ; numero.text @ = ""; } |
We're done!
Conclusions and considerations
, proprio perchè volevo lasciarlo il più semplice e snello possibile e, anche, per dimostrare che non sono elementi sempre necessari. This example does not make direct use of a UIView or UIViewController , just because I wanted to leave it as simple and streamlined as possible and, also, to show that the elements are not always necessary. However insert objects directly in the window can have some sense in this example and other sporadic contexts. portano comunque benefici in tantissimi altri casi, ein alcuni sono praticamente indispensabili; come avremo modo di vedere in futuro. The use of UIView and UIViewController bring benefits in many other cases, however, some are virtually indispensable ein, as we will see in the future.
iPhone FirstApp: Guess the number - Part 1
The first source that I rose in my hands was written in Basic and consisted of a few lines of code, for enlightening me. It was a simple game that generates a random number from 1 to 10 and, through keyboard input, verify that the number entered was Maggioni, less than or equal to the random number. Despite its rough simplicity remains, for me, one of the best examples - simple, fun and practical - to explain to those who do not know anything about programming what is meant actually for "computer program". So I decided to propose it for Apple iPhone, maybe will help someone ...








Latest Comments
Simon : It annoys disturbed again and use that space for these things ... however it does not work ...
Giovambattista Fazioli : @ Simon: what could be due to the syntax I used, specifically for PHP 5 +,...
Simon : I tried last night putting everything into functions.php, okay, jquery forms, and tabs jQueryUI them ...
Giovambattista Fazioli : @ Simon: I recommend cleaning to enter a code like that in ...
Simon : @ Giovambattista Fazioli: Thank you for your patience, it's all clear ... now I feel now, ...