Posts Tagged ‘iphone’
04
ott

Getting the Length of a String

The length of the string in a string object can be obtained by accessing the length method of the string object:

1
2
3
NSString *string1 = @"This string is Immutable";
int len = [string1 length];
NSLog (@"String length is %i", len);

Searching for a Substring

A common requirement when working with strings is to identify whether a particular sequence of characters appears within a string. This can be achieved using the rangeOfString method. This method returns a structure of type NSRange. The NSRange structure contains a location value providing the index into the string of the matched substring and a length value indicating the length of the match.

1
2
3
4
5
NSString *string1 = @"The quick brown fox jumped";
NSRange match;
match = [string1 rangeOfString: @"brown fox"];
NSLog (@"match found at index %i", match.location);
NSLog (@"match length = %i", match.length);

The NSLog call will display the location and length of the match. Note that the location is an index into the string where the match started and that the index considers the first position in a string to be 0 and not 1. As such, the location in our example will be 10 and the length will be 9.

In the event that no match is found, the rangeOfString method will set the location member of the NSRange structure to NSNotFound. For example:

1
2
3
4
5
6
7
NSString *string1 = @"The quick brown fox jumped";
NSRange match;
match = [string1 rangeOfString: @"brown dog"];
if (match.location == NSNotFound)
  NSLog (@"Match not found");
else
  NSLog (@"match found at index %i", match.location);

Replacing Parts of a String

Sections of a mutable string may be replaced by other character sequences using the replaceCharactersInRange method. This method directly modifies the string object on which the method is called so only works on mutable string objects.

This method requires two arguments. The first argument is an NSRange structure consisting of the location of the first character and the total number of characters to be replaced. The second argument is the replacement string. An NSRange structure can be created by calling NSMakeRange and passing though the location and length values as arguments. For example, to replace the word “fox” with “squirrel” in our sample mutable string object we would write the following Objective-C code:

1
2
3
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];
[string1 replaceCharactersInRange: NSMakeRange(16, 3) withString: @"squirrel"];
NSLog (@"string1 = %@", string1);

As you may have noted from the above example, the replacement string does not have to be the same length as the range being replaced. The string object and replacement method will resize the string automatically.

String Search and Replace

Previously we have covered how to perform a search in a string and how to replace a subsection of a string using the rangeOfString and replaceCharactersInRange methods respectively. The fact that both of these methods use the NSRange structure enables us to combine the two methods to perform a search and replace. In the following example, we use rangeOfString to provide us with an NSRange structure for the substring to be replace and then pass this through to replaceCharactersInRange to perform the replacement:

1
2
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];
[string1 replaceCharactersInRange: [string1 rangeOfString: @"brown fox"] withString: @"black dog"];

When executed, string1 will contain the string “The quick black dog jumped”.

Deleting Sections of a String

Similar techniques to those described above can be used to delete a subsection of a string using the deleteCharactersInRange method. As with the preceding examples, this method accepts an NSRange structure as an argument and can be combined with the rangeOfString method to perform a search and delete:

1
2
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];
[string1 deleteCharactersInRange: [string1 rangeOfString: @"jumped"]];

Extracting a Subsection of a String

A subsection of a string can be extracted using the substringWithRange method. The range is specified using an NSRange structure and the extracted substring is returned in the form of an NSString object:

1
2
3
4
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];
NSString *string2;
string2 = [string1 substringWithRange: NSMakeRange (4, 5)];
NSLog (@"string2 = %@", string2);

When executed, the above code will output the substring assigned to string2 (“quick”).

Alternatively, a substring may be extracted from a given index until the end of the string using the subStringFromIndex method. For example:

1
2
3
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];
NSString *string2;
string2 = [string1 substringFromIndex: 4];

Similarly, the subStringToIndex may be used to extract a substring from the beginning of the source string up until a specified character index into the string.

Inserting Text into a String

The insertString method inserts a substring into a string object and takes as arguments the NSString object from which the new string is to inserted and the index location into the target string where the insertion is to be performed:

1
2
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];
[string1 insertString: @"agile, " atIndex: 4];

Appending Text to the End of a String

Text can be appended to the end of an existing string object using the appendString method. This method directly modifies the string object on which the method is called and as such is only available for mutable string objects.

1
2
3
NSMutableString *string1 = [NSMutableString stringWithString: @"The quick brown fox jumped"];
[string1 appendString: @" over the lazy dog"];
NSLog (@"string1 = %@", string1);

Comparing Strings

String objects cannot be compared using the equality (==) operator. The reason for this is that any attempt to perform a comparison this way will simply compare whether the two string objects are located at the same memory location. Let’s take a look at this via an example:

1
2
3
4
5
6
NSString *string1 = @"My String";
NSString *string2 = @"My String";
if (string1 == string2)
  NSLog (@"Strings match");
else
  NSLog (@"Strings do not match");

In the above code excerpt, string1 and string2 are pointers to two different string objects both of which contain the same character strings. If we compare them using the equality operator, however, we will get a “Strings do not match” result. This is because the if (string1 == string2) test is asking whether the pointers point to the same memory location. Since string1 and string2 point to entirely different objects the answer, obviously, is no.

We can now take this a step further and change the code so that both string1 and string2 point to the same string object:

1
2
3
4
5
6
7
NSString *string1 = @"My String";
NSString *string2;
string2 = string1;
if (string1 == string2)
  NSLog (@"Strings match");
else
  NSLog (@"Strings do not match");

Now when we run the code, we get a “Strings match” result because both variables are pointing to the same object in memory.

To truly compare the actual strings contained within two string objects we must use the isEqualToString method:

1
2
3
4
5
6
NSString *string1 = @"My String";
NSString *string2 = @"My String 2";
if ([string1 isEqualToString: string2])
  NSLog (@"Strings match");
else
  NSLog (@"Strings do not match");

Another option is to use the compare method (to perform a case sensitive comparison) or the caseInsenstiveCompare NSString methods. These are more advanced comparison methods that can be useful when sorting strings into order.

Checking for String Prefixes and Suffixes

A string object can be tested to identify whether the string begins or ends with a particular sequence of characters (otherwise known as prefixes and suffixes). This is achieved using the hasPrefix and hasSuffix methods respectively, both of which return boolean values based on whether a match is found or not.

1
2
3
4
5
6
7
8
9
NSString *string1 = @"The quick brown fox jumped";
BOOL result;
result = [string1 hasPrefix: @"The"];
if (result)
  NSLog (@"String begins with The");

result = [string1 hasSuffix: @"dog"];
if (result)
NSLog (@"String ends with dog");

Converting to Upper or Lower Case

The Foundation NSString classes provide a variety of methods for modifying different aspects of case within a string. Note that each of these methods returns a new string object reflecting the change, leaving the original string object unchanged.

1
capitalizedString

Returns a copy of the specified string with the first letter of each word capitalized and all other characters in lower case:

1
2
3
NSString *string1 = @"The quicK brOwn fox jumpeD";
NSString *string2;
string2 = [string1 capitalizedString];

The above code will return a string object containing the string “The Quick Brown Fox Jumped” and assign it to the string2 variable. The string object referenced by string1 remains unmodified.

1
lowercaseString

Returns a copy of the specified string with all characters in lower case:

1
2
3
NSString *string1 = @"The quicK brOwn fox jumpeD";
NSString *string2;
string2 = [string1 lowercaseString];

The above code will return a string object containing the string “the quick brown fox jumped” and assign it to the string2 variable. The string object referenced by string1 remains unmodified.

1
uppercaseString

Returns a copy of the specified string with all characters in upper case:

1
2
3
NSString *string1 = @"The quicK brOwn fox jumpeD";
NSString *string2;
string2 = [string1 uppercaseString];

The above code will return a string object containing the string “THE QUICK BROWN FOX JUMPED” and assign it to the string2 variable. The string object referenced by string1 remains unmodified.

Converting Strings to Numbers

String objects can be converted to a variety of number types:

Convert String to int

1
2
3
NSString *string1 = @"10";
int myInt = [string1 intValue];
NSLog (@"%i", myInt);

Convert String to double

1
2
3
NSString *string1 = @"10.1092";
double myDouble = [string1 doubleValue];
NSLog (@"%f", myDouble);


Convert String to float

1
2
3
NSString *string1 = @"10.1092";
float myFloat = [string1 floatValue];
NSLog (@"%f", myFloat);

Convert String to NSInteger

1
2
3
NSString *string1 = @"10";
NSInteger myInteger = [string1 integerValue];
NSLog (@"%li", myInteger);

Converting a String Object to ASCII

The string contained within a string object can be extracted and converted to an ASCII C style character string using the UTF8String method. For example:

1
2
3
NSString *string1 = @"The quick browen fox";
const char *utfString = [string1 UTF8String];
printf ("Converted string = %s\n", utfString);

Rif: http://www.techotopia.com
Rif: albertopasca.it

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , , , , , , , , , , , , , , , , , ,

24
set

Do you want use google speech api to recognize text from a dictate?

If you want to add in your “test” project, (test project because it’s not a public API), you need to read Chrome Browser source code.

Here chromium url: src.chromium.org/viewvc/chrome/trunk/src/content/browser/speech

Chrome records audio chunks, accepts only a FLAC file, an open source audio codec (free lossless audio codec) file with a sample rate of 16000.0!

After upload to server:

https://www.google.com/speech-api/v1/recognize

and server responds with a json like this:

1
2
3
4
5
6
7
8
9
10
11
12
{
    "status": 0,
    "id": "f3847b5dcu4d657f6667f3pk4sc0a8ca-2",
    "hypotheses": [
    {
        "utterance": "it works",
        "confidence": 0.8012238
    },
    {
        "utterance": "it works"
    }]
}

Now, using ASIFormDataRequest we can send in POST a file to google url waiting for JSON.
Objective-c code:

1
2
3
4
5
6
7
8
9
10
11
12
13
- (void) SpeechFromGooglezzz {
  NSURL *url = [NSURL URLWithString:@"https://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=en-US"];

  ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
  NSString *filePath = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], @"tmpAudio.flac"];

  NSData *myData = [NSData dataWithContentsOfFile:filePath];
  [request addPostValue:myData forKey:@"Content"];
  [request addPostValue:@"audio/x-flac; rate=16000" forKey:@"Content-Type"];
  [request startSynchronous];

  NSLog(@"req: %@", [request responseString]);
}

But now is there a big problem… objective-c and iphone don’t recognize FLAC files, you need an intermediate passage to send the correct audio file.

Set up your server with FFMPEG (an audio/video converting/editing tool) and prepare a PHP/JSP/etc. that accept in post an audio file, call a PHP EXEC and launch ffmpeg with flac codec.
Then upload from server to google and return response!

Here code to record and listen audio file from iPhone. Create two buttons and copy/paste code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
- (IBAction)StartRec:(id)sender {  
  NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
                            [NSNumber numberWithFloat: 16000.0],                 AVSampleRateKey,
                            [NSNumber numberWithInt: kAudioFormatMPEGLayer3],    AVFormatIDKey,
                            [NSNumber numberWithInt: 1],                         AVNumberOfChannelsKey,
                            [NSNumber numberWithInt: AVAudioQualityMax],         AVEncoderAudioQualityKey,
                            nil];
 
  NSError *error;
  NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], @"tmpAudio.mp3"]];
  recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
 
  if (recorder) {
    [recorder prepareToRecord];
    [recorder record];
  }
  else NSLog(@"%@", [error description]);
}
1
2
3
4
5
6
7
8
9
10
11
12
- (IBAction)PlayAudio:(id)sender {
 NSString *path = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], @"tmpAudio.mp3"];
 
 SystemSoundID soundID;  
 NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
 AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
 AudioServicesPlaySystemSound(soundID);
}

- (IBAction)StopRec:(id)sender {
  if (recorder) [recorder stop];
}

That’s all, enjoy!

…and remember that speech function of google it’s a private API. You can’t use in a commercial app!

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , , , , , ,

02
ago

Cutaway App for iPhone/iPod/iPad 3.2+. [cutaway.it]

CutAway - CutAway SRL
New release 1.0.3 – bug fix.


Cutaway app mobile iphone ipad

CutAway - CutAway SRL

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , ,

07
apr

Hi all,
a promemoria to MERGE Device + Simulator libraries in a “fat” lib with XCODE.

Usage:

1. Create a static lib project
2. Select the Target
3. right-click and “Add … New Build Phase … New Run Script Build Phase”
4. Copy/paste the script below into the box

After that, customize script as you want!

In your BUILD folder you can see Release-Universal folder that contains merged libs with headers file!




Ref: albertopasca.it

Here the 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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
### EXECUTED ONLY WITH SIMULATOR->RELEASE->MyTarget

#!/bin/sh

### CONFIG VARS
MY_TARGET="MyTarget"
IS_VALID="FALSE"
SDK_VERSION=$(echo ${SDK_NAME} | grep -o '.\{3\}$')
ALREADYINVOKED="false"
UNIVERSAL_NAME="Release-universal"
BUILD_DEV_PATH=${BUILD_DIR}/${UNIVERSAL_NAME}/tmp-dev/
BUILD_SIM_PATH=${BUILD_DIR}/${UNIVERSAL_NAME}/tmp-sim/

### CONF CHECK
CheckConfig() {
 # YOUR COMPILE RULES
 if [ ${CONFIGURATION} == "Release" ] &&
    [ ${ACTION} == "build" ] &&
    [ ${TARGET_NAME} == ${MY_TARGET} ] &&
    [ ${PLATFORM_NAME} == "iphonesimulator" ]
 then
  IS_VALID="TRUE"
 fi
}

### MKDIRS
CreateFolders() {
 mkdir -p "${SYMROOT}/${UNIVERSAL_NAME}/"
 mkdir -p  ${BUILD_DEV_PATH}
 mkdir -p  ${BUILD_SIM_PATH}
 mkdir -p "${SYMROOT}/${UNIVERSAL_NAME}/include"
}

### MULTIPLE BUILDS
BuildLibs() {
 # BUILD DEVICE
 xcodebuild -configuration "Release" -target "PGLib" -sdk "iphoneos4.3" build RUN_CLANG_STATIC_ANALYZER=NO BUILD_DIR="${BUILD_DEV_PATH}" BUILD_ROOT="${BUILD_DEV_PATH}"
 # BUILD SIMULATOR
 xcodebuild -configuration "Release" -target "PGLib_Simulator" -sdk "iphonesimulator4.3" build RUN_CLANG_STATIC_ANALYZER=NO BUILD_DIR="${BUILD_SIM_PATH}" BUILD_ROOT="${BUILD_SIM_PATH}"
}

### MERGE LIBS
FatLibs() {
 LIB_DEV="${BUILD_DEV_PATH}/Release-iphoneos/libPGLib-DEV.a"
 LIB_SIM="${BUILD_SIM_PATH}/Release-iphonesimulator/libPGLib-SIM.a"
 LIB_UNI="${SYMROOT}/${UNIVERSAL_NAME}/libPGLib.a"
 HEADERS="${BUILD_DEV_PATH}/Release-iphoneos/usr/local/include/"

 cp "${HEADERS}"/* "${SYMROOT}/${UNIVERSAL_NAME}/include"

 lipo -create "${LIB_DEV}" "${LIB_SIM}" -output "${LIB_UNI}"
}

### CLEAN WORKING DATA
ClearTemporary() {
 rm -rf "${BUILD_DEV_PATH}"
 rm -rf "${BUILD_SIM_PATH}"
}

#
### MAIN
#
if [ "true" != ${ALREADYINVOKED:-false} ]; then  # SKIP APPLE RECURSION
 CheckConfig
 ALREADYINVOKED="true"

 if [ ${IS_VALID} == "TRUE" ]; then  # DO WORK
  CreateFolders
  BuildLibs
  FatLibs
  ClearTemporary

  echo "Custom script on RELEASE/SIMULATOR/${MY_TARGET} executed!";
 else
  echo "Custom script SKIPPED execution!";
 fi
fi

enjoy coding!!!






Ref: albertopasca.it

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , ,

11
gen

Get current and formatted time from your simulator or device!

1
2
3
4
5
6
7
8
9
10
11
12
13
- (NSString*) getDateTime {
     NSDateFormatter *formatter;
     NSString        *dateString;
 
     formatter = [[NSDateFormatter alloc] init];
     [formatter setDateFormat:@"dd-MM-yyyy HH:mm"];
 
     dateString = [formatter stringFromDate:[NSDate date]];
     [formatter release];

     NSLog(@"Current data: %@", dateString);
     return dateString;
}

eof

Rif: albertopasca.it

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , ,

10
gen

Hi all,
with these lines of code you can use Apple iOS Mail system to send an email with an attachment!





It’s so easy that i don’t know this method!

First, import MessageUI framework, after include in your header file (.h) the import to the framework:

1
#import messageui/MessageUI.h

and set the delegate to

1
mfmailcomposeviewcontrollerdelegate

Now, create a button in your view and attach mailil function!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
- (void) mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult: (MFMailComposeResult)result error:(NSError*)error {
 [self dismissModalViewControllerAnimated:YES];
}

- (IBAction) mailIt {
 MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
 picker.mailComposeDelegate = self;
 
 [picker setSubject:@"This is the subject"];
 
 UIImage *roboPic = [UIImage imageNamed:@"anImage.jpg"];
 NSData *imageData = UIImageJPEGRepresentation(roboPic, 1);
 [picker addAttachmentData:imageData mimeType:@"image/jpg" fileName:@"anImage.jpg"];
 
 NSString *emailBody = @"This is the email body!!";
 [picker setMessageBody:emailBody isHTML:YES];
 
 [self presentModalViewController:picker animated:YES];
 [picker release];
}

done!





Rif: albertopasca.it

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , ,

09
gen

Hi all,
this is a simple way to add programmatically a “Person” into your iphone contacts list.

First of all you need to include Address Book frameworks into your project:

#import AddressBook/AddressBook.h
#import AddressBookUI/AddressBookUI.h





After that, create an IBAction or something else and paste this function:

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
- (IBAction) addToContacts {
        ABAddressBookRef iPhoneAddressBook = ABAddressBookCreate();
        ABRecordRef newPerson = ABPersonCreate();

        // add infos
        ABRecordSetValue(newPerson, kABPersonFirstNameProperty, CFSTR("Alberto"), nil);
        ABRecordSetValue(newPerson, kABPersonLastNameProperty, CFSTR("Pasca"), nil);
        ABRecordSetValue(newPerson, kABPersonOrganizationProperty, CFSTR("albertopasca.it"), nil);

        ABMutableMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiStringPropertyType);
 
        ABMultiValueAddValueAndLabel(multiPhone, @"328-1111111", kABHomeLabel, NULL);
        ABMultiValueAddValueAndLabel(multiPhone,@"02-222222", kABWorkLabel, NULL);
        ABRecordSetValue(newPerson, kABPersonPhoneProperty, multiPhone,nil);
        CFRelease(multiPhone);
 
        ABMutableMultiValueRef multiEmail = ABMultiValueCreateMutable(kABMultiStringPropertyType);

        ABMultiValueAddValueAndLabel(multiEmail, @"info@albertopasca.it", kABHomeLabel, NULL);
        ABRecordSetValue(newPerson, kABPersonEmailProperty, multiEmail, nil);

        // add an image !
        UIImage *im = [UIImage imageNamed:@"logo_mobile_48.png"];
        NSData *dataRef = UIImagePNGRepresentation(im);
        ABPersonSetImageData(newPerson, (CFDataRef)dataRef, nil);

        CFRelease(multiEmail);
 
        ABAddressBookAddRecord(iPhoneAddressBook, newPerson, nil);
        BOOL didAdd = ABAddressBookSave(iPhoneAddressBook, nil);

        CFRelease(newPerson);
        CFRelease(iPhoneAddressBook);
}

All the contact properties are hidden in kAB*******. Try it!

It’s all!!!

enjoy!




Rif: albertopasca.it

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , , , , ,

30
nov





Può capitare di avere un textfield in basso nella view
Come ben sapete, la tastiera che appare, copre mezzo schermo, e questo può essere noioso.

Lo si capisce meglio dall’esempio in foto:






Ecco qui, un trick per evitare questo problemino…

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
37
38
int verticalOffset;

#pragma mark TEXTFIELD_TRICKS

- (BOOL) textFieldShouldReturn:(UITextField *)textField {
 [textField resignFirstResponder];
 
 if (verticalOffset != 0) {
  [self moveView: -verticalOffset + 200];
  verticalOffset = 0;
 }
 return YES;
}

- (void) textFieldDidBeginEditing:(UITextField *)textField {
 
 int wantedOffset = textField.frame.origin.y - 200;
 if ( wantedOffset < 0 ) {
  wantedOffset = 0;
 }
 if ( wantedOffset != verticalOffset ) {
  [self moveView: wantedOffset - verticalOffset];
  verticalOffset = wantedOffset;
 }
}

- (void) moveView:(int)offset {
 [UIView beginAnimations:nil context:NULL];
 [UIView setAnimationDuration:0.3];
 
 CGRect rect = self.view.frame;
 rect.origin.y -= offset;
 rect.size.height += offset;
 
 VIEW_TO_MOVE.frame = rect;
 
 [UIView commitAnimations];
}

Adesso la vostra view si sposterà in alto, per poi ritornare a casa!
Ovviamente offset e impostazioni sono personalizzabilissime.





FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , ,

27
ott

Here a simple tutorial to use SQLite in Objective-C to make complex iphone|ipad applications that uses a database!

First of all, you NEED to download Firefox, after that you need to download and install SQLite Manager Add On for Firefox from here.
The plugin will be used later…

Now, create a new project and import SQLite library. Generally it is located here:

/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.X.X.X.sdk/usr/lib/libsqlite3.dylib

Firefox!

In your header file, you need t add the import and create sqlite3 class in your interface:

1
2
3
#import <sqlite3 .h>
[...]
sqlite3 *database;

I show only three method that uses the db, SELECT, DELETE, INSERT.





READ DATA (like SELECT * FROM XXX)

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
- (NSMutableArray*) readDataFromDatabase
{
   dataArray  = [[NSMutableArray alloc] init];
   dataStored = [[NSMutableDictionary alloc] init];
   
   NSString *name;
   NSString *address;
 
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
   NSString *documentsDirectory = [paths objectAtIndex:0];
   NSString *path = [documentsDirectory stringByAppendingPathComponent:@"MyDB.sqlite"];
 
   if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
      const char *sql = "SELECT * FROM tabella";
      sqlite3_stmt *statement;
      if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
         while (sqlite3_step(statement) == SQLITE_ROW) {
            name =   [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
            address = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
   
            [dataStored setObject:name forKey:@"name"];
            [dataStored setObject:address forKey:@"address"];
   
            [dataArray addObject:[dataStored copy]];
         }
      }
      sqlite3_finalize(statement);
   }
   sqlite3_close(database);
   [dataStored release];

   return dataArray;
}

In this method, that return a NSMutableArray, I used a NSMutableDictionary (dataStored) and a NSMutableArray (dataArray).
Now we have a dataArray with lists of the select query!

Continue reading “[Objective-C] Use database with sql (lite)” »

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , , , ,

Switch to our mobile site