Monday, December 13, 2010

UIscrollview Swipped page Number

- (void)scrollViewDidEndDecelerating:(UIScrollView *)sender {
// We don't want a "feedback loop" between the UIPageControl and the scroll delegate in
// which a scroll event generated from the user hitting the page control triggers updates from
// the delegate method. We use a boolean to disable the delegate logic when the page control is used.
if (sender.tag!=789012) {
return;
}


// Switch the indicator when more than 50% of the previous/next page is visible
CGFloat pageWidth = bannerScrollView.frame.size.width;
int page = floor((bannerScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
NSLog(@"Page Count %d",page);


}

Wednesday, September 29, 2010

Image Caching Algorithm

http://www.iphonedevsdk.com/forum/iphone-sdk-tutorials/13315-image-caching-tutorial.html

Tuesday, September 14, 2010

String to Url String in iphone sdk

NSString* escapedUrlString =[unescapedString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

Sunday, July 11, 2010

Working with Directories on iPhone OS

REFERENCE
http://www.techotopia.com/index.php/Working_with_Directories_on_iPhone_OS


Creating an NSFileManager Instance Object


NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];

Identifying the Current Working Directory :
As previously mentioned, when an application first loads its current working directory is the application’s root directory, represented by a / character. The current working directory may be identified at any time through a call to the currentDirectoryPath method of the file manager object. For example, the following code fragment identifies the current working directory:
NSFileManager *filemgr; NSString *currentPath;

filemgr =[NSFileManager defaultManager];
currentPath = [filemgr currentDirectoryPath];
[filemgr release];

Identifying the Documents Directory

NSArray *dirPaths;
NSString *docsDir;

dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);

docsDir = [dirPaths objectAtIndex:0];


/Users//Library/Application Support/iPhone Simulator/User/Application//Documents

Identifying the Temporary Directory:

In addition to the Documents directory, iPhone applications are also provided with a tmpNSTemporaryDirectory C function as follows: directory for the storage of temporary files. The path to the current application’s temporary directory may be ascertained with a call to the

NSString *tmpDir = NSTemporaryDirectory();

Changing Directory:

Having identified the path to the application’s document or temporary directory the chances are good that you will need to make that directory the current working directory. The current working directory of a running iPhone application can be changed with a call to the changeCurrentDirectoryPath method of an NSFileManager class instance. The destination directory path is passed as an argument to the instance method in the form of an NSString object. Note that this method returns a boolean YES or NO result to indicate if the requested directory change was successful or not. A failure result typically indicates that the specified directory does not exist, or that the application lacks the appropriate access permissions:

NSFileManager *filemgr;
NSArray *dirPaths;
NSString *docsDir;

filemgr =[NSFileManager defaultManager];

dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

docsDir = [dirPaths objectAtIndex:0];

if ([filemgr changeCurrentDirectoryPath: docsDir] == NO)
{
// Directory does not exist – take appropriate action
}

Creating a New Directory

A new directory is created using the createDirectoryAtPath instance method of the NSFileManager class, once again passing through the pathname of the new directory as an argument and returning a boolean success or failure result. This method also takes an additional argument in the form a set of attributes for the new directory. Specifying nil will use the default attributes.

The following code fragment identifies the Documents directory and creates a new sub-directory named data in that directory:
NSFileManager *filemgr;
NSArray *dirPaths;
NSString *docsDir;
NSString *newDir;
filemgr =[NSFileManager defaultManager];
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
newDir = [docsDir stringByAppendingPathComponent:@"data"];
if ([filemgr createDirectoryAtPath:newDir attributes:nil] == NO)
{ // Failed to create directory }
[filemgr release];


Deleting a Directory

An existing directory may be removed from the file system using the removeItemAtPath method, passing though the path of the directory to be removed as an argument. For example, to remove the data directory created in the preceding example we might write the following code:
NSFileManager *filemgr;
NSArray *dirPaths;
NSString *docsDir; NSString *newDir;
filemgr =[NSFileManager defaultManager];
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
newDir = [docsDir stringByAppendingPathComponent:@"data"];
if ([filemgr removeItemAtPath: newDir error: nil] == NO)
{
// Directory removal failed.
}
[filemgr release];

Listing the Contents of a Directory

A listing of the files contained within a specified directory can be obtained using the directoryContentsAtpath method. This method takes the directory pathname as an argument and returns an NSArray object containing the names of the files and sub-directories in that directory. The following example obtains a listing of the contents of the root directory (/) and displays each item in the Console window application (located in the /Applications/Utilities folder of your Mac OS X system). Note that since there is no Console for the iPhone device, the output will only be visible when the application is running in the simulator environment:

NSFileManager *filemgr;
NSArray *filelist;
int count;
int i;

filemgr =[NSFileManager defaultManager];

filelist = [filemgr directoryContentsAtPath:@"/"];

count = [filelist count];

for (i = 0; i < count; i++)
NSLog(@"%@", [filelist objectAtIndex: i]);
[filemgr release];

Getting the Attributes of a File or Directory

The attributes of a file or directory can be obtained using the attributesOfItemAtPath method. This takes as arguments the path of the directory and an optional NSError object into which information about any errors will be placed (may be specified as NULL if this information is not required). The results are returned in the form of an NSDictionary dictionary object. The keys for this dictionary are as follows:

NSFileType
NSFileTypeDirectory
NSFileTypeRegular
NSFileTypeSymbolicLink
NSFileTypeSocket
NSFileTypeCharacterSpecial
NSFileTypeBlockSpecial
NSFileTypeUnknown
NSFileSize
NSFileModificationDate
NSFileReferenceCount
NSFileDeviceIdentifier
NSFileOwnerAccountName
NSFileGroupOwnerAccountName
NSFilePosixPermissions
NSFileSystemNumber
NSFileSystemFileNumber
NSFileExtensionHidden
NSFileHFSCreatorCode
NSFileHFSTypeCode
NSFileImmutable
NSFileAppendOnly
NSFileCreationDate
NSFileOwnerAccountID
NSFileGroupOwnerAccountID

For example, we can extract the file type and POSIX permissions for the /Applications directory using the following code excerpt:

NSFileManager *filemgr;
NSDictionary *attribs;

filemgr = [NSFileManager defaultManager];

attribs = [filemgr attributesOfItemAtPath: @"/Applications" error: NULL];

NSLog (@"File type %@", [attribs objectForKey: NSFileType]);
NSLog (@"POSIX Permissions %@", [attribs objectForKey: NSFilePosixPermissions]);

[filemgr release];

File I/O Functions: A Tutorial for Software Developers

http://www.servin.com/iphone/iPhone-File-IO.html

Servin Mobile Software


How to use iPhone with File I/O Functions: A Tutorial for Software Developers


Norman McEntire

Version 1.4 Sep 1. Thank you Freedy.

Version 1.3 Aug 6. Thank you Chris B.

Version 1.2 May 1. Thank you Pierre M.

Version 1.1 January 20

Copyright © 2009 Servin Corporation. http://servin.com


Introduction

The iPhone OS, like Mac OS X, provides both Apple specific file I/O functions, and Unix-type file I/O functions.

For example, you can use Apple specific functions to find the paths related to your application. You can also use Apple specific Object-C classes to read/write files.

An alternative is to use Unix-specific functions to read/write files. In addition to the standard open/close/read/write, you can do memory mapping, where the file is mapped directly into your address space.

In this Servin Mini-Course, you will learn how to use Apple-specific functions and class methods to perform file I/O.


iPhone Software Skills You Will Learn

  • How to use Xcode to create a Window-Based App.
  • How to display text output in a UITextView control.
  • How to use NSBundle to find the resource path.
  • How to use NSString to read a file.
  • How to use NSSearchPathForDirectoriesInDomains() to find common search paths.

Prerequisites


Startup Xcode

If Xcode is not already running, start it up:

  1. On the Mac Desktop, double-click on the Finder icon (the icon with the face on it).
  2. On the left-side of the Finder window, click on Macintosh HD.
  3. On the right-side of the Finder window, click on the Developer folder.
  4. Click on the Applications folder.
  5. Double-click on the Xcode icon.

At this point, you should see the Xcode menu at the top of your desktop.


Create New Xcode Project

With Xcode running, create a new Xcode project:

  1. File > New Project.
  2. On the left-side of the New Project window, select Application under iPhone OS.
  3. On the right-side of the New Project window, select Window-Based Application.
  4. Click on the Choose button.
  5. Enter FileIo for the project name.
  6. Click on Save button.

At this point, you should see Xcode open a new window that shows a number of files.


Build Default App

Go ahead and build the default application:

  1. Click on the Build and Go button.
  2. After a brief moment, you should see the code running in the iPhone Simulator.
  3. Observe the status bar at the top of the window, and a white window everywhere else.
  4. In the iPhone Simulator, press the Home button to stop the application.

Edit FileIoAppDelegate to Add UITextView as Subview to UIWindow

In this exercise, you will edit FileIoAppDelegate.h and FileIoAppDelegate.m to add a UITextView as a subview to the UIWindow.

  1. In Xcode, in the Groups & Files window on the left-side, click on the Classes folder.
  2. You should see the following files on the right-side of the window:
    FileIoAppDelegate.h
    FileIoAppDelegate.m
  3. Select FileIoAppDelegate.h so that it appears in the Xcode editor window.
  4. Edit the code to match the following:
    #import 

    @interface FileIoAppDelegate : NSObject {
    UIWindow *window;

    UITextView *textView;

    }
    @property (nonatomic, retain) IBOutlet UIWindow *window;

    @property (nonatomic, retain) UITextView *textView;

    @end
  5. The above code adds a member variable named textView, which is a pointer to an object of type UITextView. Our goal is to use the UITextView control to display the output.
  6. We will not use Interface Builder for this demo, so we did not add the IBOutlet to the code that we entered.
  7. Select FileIoAppDelegate.m into the Xcode editor window.
  8. Edit the code to match the following:
    #import 

    @implementation FileIoAppDelegate

    @synthesize window;

    @synthesize textView;


    - (void)applicationDidFinishLaunching:(UIApplication *)application {

    // Create instance of UITextView
    self.textView = [[UITextView alloc]
    initWithFrame:[[UIScreen mainScreen] applicationFrame]];

    // Add text
    self.textView.text = @"Output will go here...";

    // Make non-editable
    self.textView.editable = NO;

    // Add as subview to window
    [window addSubview:self.textView];

    // Decrement our usage count
    [self.textView release];

    [window makeKeyAndVisible];
    }
  9. Build and Go.
  10. You should see your app running, with the text "Output will go here..." displayed in the window.
  11. Press Home in iPhone Simulator to stop the application.

As a review, in this exercise you added code to the FileIoAppDelegate class to create a UITextView, setting it so that it cannot be edited. You also added text to the UITextView, and then added the UITextView to the subview of the window.


Create MyFile.txt

In this exercise, you will create a file named MyFile.txt as a sample text file that you will later read and display in the iPhone window.

  1. In Xcode, in the Groups & Files window on the left-side, click on the Resources folder.
  2. You should see the following frameworks:
    - Info.plist
    - MainWindow.xib
  3. Control+click on the Resources folder.
  4. Select Add from the popup menu.
  5. Select New File.
  6. In the New File window, on the left-side of the window, under the category Mac OS X, click on Other.
  7. In the New File window, on the right-side of the window, click on Empty File.
  8. Click on Next.
  9. Name the file MyFile.txt.
  10. Click on Finish.
  11. Under the Resources folder, you should now have three files:
    - MainWindow.xib
    - Info.plist
    - MyFile.txt
  12. Click on MyFile.txt to select it into the Xcode editor.
  13. Enter the following into the file:
    This is a text file.
    The file will be displayed on the iPhone.
    That is all for now.

As a review, you created a text file named MyFile.txt in the Resources directory of your project.


NSHomeDirectory()

In this exercise, you will use the NSHomeDirectory() function to retrieve the path to the home directory of your application:

NSString *NSHomeDirectory(void);

An important point: the location of your home directory is different depending on whether you are running on the iPhone Simulator or on an actual device (iPhone or iPod Touch).

  1. In Xcode, in the Groups & Files window on the left-side, click on the Classes folder.
  2. You should see the following files:
    - FileIoAppDelegate.h
    - FileIoAppDelegate.m
  3. Click on FileIoAppDelegate.m to select it into the Xcode editor.
  4. Edit the code to match the following:
    #import 

    @implementation FileIoAppDelegate

    @synthesize window;
    @synthesize textView;

    - (void)applicationDidFinishLaunching:(UIApplication *)application {

    // Create instance of UITextView
    self.textView = [[UITextView alloc]
    initWithFrame:[[UIScreen mainScreen] applicationFrame]];

    NSString *homeDir = NSHomeDirectory();

    // Add text
    self.textView.text = homeDir;


    // Make non-editable
    self.textView.editable = NO;

    // Add as subview to window
    [window addSubview:self.textView];

    // Decrement our usage count
    [self.textView release];

    [window makeKeyAndVisible];
    }
  5. Build and Go.
  6. When your application runs, you should see a path similar to the following displayed on the screen (the value will change based on whether you are on the iPhone Simulator or the iPhone device):
    /Users/student/Library/Application Support/iPhone/Simulator/User/Applications/...

    - OR (on an actual device) -

    /var/mobile/Applications/...

As a review, in this exercise you used the NSHomeDirectory() function to find the pathname of your applications home directory.


NSTemporaryDirectory()

In this exercise, you will use the NSTemporaryDirectory() function to retrieve the path to the temporary directory for use by your application.

NSString *NSTemporaryDirectory(void);

An important point: the location of your temporary directory is different depending on whether you are running on the iPhone Simulator or on an actual device (iPhone or iPod Touch).

  1. In Xcode, click on FileIoAppDelegate.m to select it into the Xcode editor.
  2. Edit the code to match the following:
    #import 

    @implementation FileIoAppDelegate

    @synthesize window;
    @synthesize textView;

    - (void)applicationDidFinishLaunching:(UIApplication *)application {

    // Create instance of UITextView
    self.textView = [[UITextView alloc]
    initWithFrame:[[UIScreen mainScreen] applicationFrame]];

    // Get home directory
    NSString *homeDir = NSHomeDirectory();


    // Get temporary directory
    NSString *tempDir = NSTemporaryDirectory();

    // Format output
    NSString *s =
    [NSString stringWithFormat:@"homeDir:\n"
    @"%@\n"
    @"tempDir:\n"
    @"%@\n",
    homeDir,
    tempDir];
    // Add text
    self.textView.text = s;


    // Make non-editable
    self.textView.editable = NO;

    // Add as subview to window
    [window addSubview:self.textView];

    // Decrement our usage count
    [self.textView release];

    [window makeKeyAndVisible];
    }
  3. Build and Go.
  4. When your application runs, you should see output similar to the following (the values will change based on whether you are on the iPhone Simulator or the iPhone device):
    homeDir:
    /Users/student/Library/Application Support/iPhone/Simulator/User/Applications/...
    tempDir:
    /var/folders/7m/....

    - OR (on an actual device)
    /private/var/mobile/Applications/.../tmp

As a review, in this exercise you used the NSTemporaryDirectory() function.


NSSearchPathForDirectoriesInDomains()

In this exercise, you will use the NSSearchPathForDirectoriesInDomains() function to retrieve various paths:

NSArray *
NSSearchPathForDirectoriesInDomains(
NSSearchPathDirectory directory, //NSDocumentDirectory or NSCachesDirectory
NSSearchpathDomainMask domainMask, //NSUserDomainMask
BOOL exppandTilde); // YES

An important point: Although a NSArray object is returned, you will only use the first array entry (index 0), which will contain an NSString.

  1. In Xcode, click on FileIoAppDelegate.m to select it into the Xcode editor.
  2. Edit the code to match the following:
    #import 

    @implementation FileIoAppDelegate

    @synthesize window;
    @synthesize textView;

    - (void)applicationDidFinishLaunching:(UIApplication *)application {

    // Create instance of UITextView
    self.textView = [[UITextView alloc]
    initWithFrame:[[UIScreen mainScreen] applicationFrame]];

    // Get home directory
    NSString *homeDir = NSHomeDirectory();

    // Get temporary directory
    NSString *tempDir = NSTemporaryDirectory();


    // Get documents directory
    NSArray *arrayPaths =
    NSSearchPathForDirectoriesInDomains(
    NSDocumentDirectory,
    NSUserDomainMask,
    YES);

    NSString *docDir = [arrayPaths objectAtIndex:0];

    // Format output
    NSString *s =
    [NSString stringWithFormat:@"homeDir:\n"
    @"%@\n"
    @"tempDir:\n"
    @"%@\n"
    @"docDir:\n"
    @"%@\n",
    homeDir,
    tempDir,
    docDir];

    // Add text
    self.textView.text = s;

    // Make non-editable
    self.textView.editable = NO;

    // Add as subview to window
    [window addSubview:self.textView];

    // Decrement our usage count
    [self.textView release];

    [window makeKeyAndVisible];
    }
  3. Build and Go.
  4. When your application runs, you should see output similar to the following:
    homeDir:
    /Users/student/Library/Application Support/iPhone/Simulator/User/Applications/...
    tempDir:
    /var/folder/7m/....
    docDir:
    /Users/student/Library/Application Support/.../Documents

As a review, in this exercise you used the NSSearchPathForDirectoriesInDomain() function.


Using NSBundle and pathForResource:ofType:

In this exercise, you will use the NSBundle class to report the path to the applications resources. The applications resources are stored in the application bundle, and the path to this bundle can be found with the method pathForRecoure:ofType:.

  1. In Xcode, click on FileIoAppDelegate.m to select it into the Xcode editor.
  2. Edit the code to match the following:
    #import 

    @implementation FileIoAppDelegate

    @synthesize window;
    @synthesize textView;

    - (void)applicationDidFinishLaunching:(UIApplication *)application {

    // Create instance of UITextView
    self.textView = [[UITextView alloc]
    initWithFrame:[[UIScreen mainScreen] applicationFrame]];

    // Get home directory
    NSString *homeDir = NSHomeDirectory();

    // Get temporary directory
    NSString *tempDir = NSTemporaryDirectory();

    // Get documents directory
    NSArray *arrayPaths =
    NSSearchPathForDirectoriesInDomains(
    NSDocumentDirectory,
    NSUserDomainMask,
    YES);

    NSString *docDir = [arrayPaths objectAtIndex:0];


    NSString *myFilePath = [[NSBundle mainBundle]
    pathForResource:@"MyFile"
    ofType:@"txt"];

    // Format output
    NSString *s =
    [NSString stringWithFormat:@"homeDir:\n"
    @"%@\n"
    @"tempDir:\n"
    @"%@\n"
    @"docDir:\n"
    @"%@\n"
    @"myFilePath:\n"
    @"%@\n",
    homeDir,
    tempDir,
    docDir,
    myFilePath];

    // Add text
    self.textView.text = s;

    // Make non-editable
    self.textView.editable = NO;

    // Add as subview to window
    [window addSubview:self.textView];

    // Decrement our usage count
    [self.textView release];

    [window makeKeyAndVisible];
    }
  3. Build and Go.
  4. When your application runs, you should see output similar to the following:
    homeDir:
    /Users/student/Library/Application Support/iPhone/Simulator/User/Applications/...
    tempDir:
    /var/folder/7m/....
    docDir:
    /Users/student/Library/Application Support.../Documents
    myFilePath:
    /Users/student/Library/Application Support/.../FileIo.App/MyFile.txt

As a review, in this exercise you used the NSBundle class to determine the path to the MyFile.txt, which is stored as part of the resource bundle.


Using NSString and stringWithContentsOfFile:encoding:error:

In this exercise, you will use the NSString class to read the MyText.txt file.

  1. In Xcode, click on FileIoAppDelegate.m to select it into the Xcode editor.
  2. Edit the code to match the following:
    #import 

    @implementation FileIoAppDelegate

    @synthesize window;
    @synthesize textView;

    - (void)applicationDidFinishLaunching:(UIApplication *)application {

    // Create instance of UITextView
    self.textView = [[UITextView alloc]
    initWithFrame:[[UIScreen mainScreen] applicationFrame]];

    // Get home directory
    NSString *homeDir = NSHomeDirectory();

    // Get temporary directory
    NSString *tempDir = NSTemporaryDirectory();

    // Get documents directory
    NSArray *arrayPaths =
    NSSearchPathForDirectoriesInDomains(
    NSDocumentDirectory,
    NSUserDomainMask,
    YES);

    NSString docDir = [arrayPaths objectAtIndex:0];

    NSString *myFilePath = [[NSBundle mainBundle]
    pathForResource:@"MyFile"
    ofType:@"txt"];


    NSString *myFileContents = [NSString stringWithContentsOfFile:myFilePath
    encoding:NSUTF8StringEncoding
    error:nil];

    // Format output
    NSString *s =
    [NSString stringWithFormat:@"homeDir:\n"
    @"%@\n"
    @"tempDir:\n"
    @"%@\n"
    @"docDir:\n"
    @"%@\n"
    @"myFilePath:\n"
    @"%@\n"
    @"Contents of file:\n"
    @"%@\n",
    homeDir,
    tempDir,
    docDir,
    myFilePath,
    myFileContents];

    // Add text
    self.textView.text = s;

    // Make non-editable
    self.textView.editable = NO;

    // Add as subview to window
    [window addSubview:self.textView];

    // Decrement our usage count
    [self.textView release];

    [window makeKeyAndVisible];
    }
  3. Build and Go.
  4. When your application runs, you should see output similar to the following:
    homeDir:
    /Users/student/Library/Application Support/iPhone/Simulator/User/Applications/...
    tempDir:
    /var/folder/7m/....
    docDir:
    /Users/student/Library/Application Support/.../Documents
    myFilePath:
    /Users/student/Library/Application Support/.../FileIo.App/MyFile.txt
    Contents of file:
    This is a text file.
    This file will be displayed on the iPhone.
    That is all for now.

As a review, in this exercise you used the NSString class to read the contents of MyFile.txt.


Using NSString and writeFileTo:atomically:encoding:

In this exercise, you will use the NSString class to write a new file named NewText.txt.

  1. In Xcode, click on FileIoAppDelegate.m to select it into the Xcode editor.
  2. Edit the code to match the following:
    #import 

    @implementation FileIoAppDelegate

    @synthesize window;
    @synthesize textView;

    - (void)applicationDidFinishLaunching:(UIApplication *)application {

    // Create instance of UITextView
    self.textView = [[UITextView alloc]
    initWithFrame:[[UIScreen mainScreen] applicationFrame]];

    // Get home directory
    NSString *homeDir = NSHomeDirectory();

    // Get temporary directory
    NSString *tempDir = NSTemporaryDirectory();

    // Get documents directory
    NSArray *arrayPaths =
    NSSearchPathForDirectoriesInDomains(
    NSDocumentDirectory,
    NSUserDomainMask,
    YES);

    NSString docDir = [arrayPaths objectAtIndex:0];

    NSString *myFilePath = [[NSBundle mainBundle]
    pathForResource:@"MyFile"
    ofType:@"txt"];

    NSString *myFileContents = [NSString stringWithContentsOfFile:myFilePath
    encoding:NSUTF8StringEncoding
    error:nil];

    // Format output
    NSString *s =
    [NSString stringWithFormat:@"homeDir:\n"
    @"%@\n"
    @"tempDir:\n"
    @"%@\n"
    @"docDir:\n"
    @"%@\n"
    @"myFilePath:\n"
    @"%@\n"
    @"Contents of file:\n"
    @"%@\n",
    homeDir,
    tempDir,
    docDir,
    myFilePath,
    myFileContents];

    // Create pathname to Documents directory
    NSString *newFilePath = [docDir stringByAppendingString:@"/NewFile.txt"];

    // Write string to file
    [s writeToFile:newFilePath
    atomically:YES
    encoding:NSUTF8StringEncoding
    error:nil];

    // Add text
    self.textView.text = s;

    // Make non-editable
    self.textView.editable = NO;

    // Add as subview to window
    [window addSubview:self.textView];

    // Decrement our usage count
    [self.textView release];

    [window makeKeyAndVisible];
    }
  3. Build and Go.
  4. When your application runs, it displays output on the iPhone screen, and also writes the output to the NewFile.txt file.
  5. While the iPhone Simulator is still running, open up a terminal window, and cat (concatenate) out the contents of the file:
    $ cat /Users/student/Library/Application Support/.../Documents/NewFile.txt
    ...

As a review, in this exercise you used the NSString class to write the contents of a NSString MyFile.txt.


Skills Review

  • Xcode
  • Window-Based Application
  • UITextView
  • NSHomeDirectory()
  • NSTemporaryDirectory()
  • NSSearchPathForDirectoriesInDomains()
  • NSBundle
  • mainBundle
  • pathForResource:ofType:
  • NSString
  • stringWithContentsOfFile:encoding:error:
  • writeToFile:atomically:encoding:error:

Wednesday, June 23, 2010

Stop animation

UIView *viewBeingAnimated = //your view that is being animated
viewBeingAnimated
.frame = [[viewBeingAnimated.layer presentationLayer] frame];
[viewBeingAnimated.layer removeAllAnimations];



another way


Another option is to set the image property as well as the animationImages property. Doing this will display the static image when the UIImageView has its animations stopped.

Assuming your class is a subclass of UIImageView and have an NSMutableArray of images, do the following:

self.animationImages = images;
//yes, I'm skipping the step to check and make sure you have at least one
//element in your array
self.image = [images objectAtIndex: 0];

Tuesday, June 15, 2010

save screen image of iphone

 CGRect myRect = [myView bounds];
UIGraphicsBeginImageContext(myRect.size);

CGContextRef ctx = UIGraphicsGetCurrentContext();
[[UIColor blackColor] set];
CGContextFillRect(ctx, myRect);

[myView.layer renderInContext:ctx];

UIImage *image1 = UIGraphicsGetImageFromCurrentImageContext();

// Replace the following line with code that emails the image
UIImageWriteToSavedPhotosAlbum(image1, nil, nil, nil);
UIGraphicsEndImageContext();

Sample login in iphone

http://www.riccomini.name/Topics/Mobile/iPhone/SimpleLoginScreen/

Friday, June 4, 2010

NsTimer

1) scheduled timer & using selector

NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 2.0
                      target: self
                      selector
:@selector(onTick:)
                      userInfo
: nil repeats:NO];
  • if you set repeats to NO, the timer will wait 2 seconds before running the selector and after that it will stop;
  • if repeat: YES, the timer will start immediatelly and will repeat calling the selector every 2 seconds;
  • to stop the timer you call the timer's -invalidate method: [t invalidate];

As a side note, instead of using a timer that doesn't repeat and calls the selector after a specified interval, you could use a simple statement like this:

[self performSelector:@selector(onTick:) withObject:nil afterDelay:2.0];
this will have the same effect as the sample code above; but if you want to call the selector every nth time, you use the timer with repeats:YES

2) self-scheduled timer
   NSDate *d = [NSDate dateWithTimeIntervalSinceNow: 60.0];
NSTimer *t = [[NSTimer alloc] initWithFireDate: d
                              interval
: 1
                              target
: self
                              selector
:@selector(onTick:)
                              userInfo
:nil repeats:YES];

NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:t forMode: NSDefaultRunLoopMode];
[t release];
  • this will create a timer that will start itself on a custom date specified by you (in this case, after a minute), and repeats itself every one second 
 

3) unscheduled timer & using invocation

NSMethodSignature *sgn = [self methodSignatureForSelector:@selector(onTick:)];
NSInvocation *inv = [NSInvocation invocationWithMethodSignature: sgn];
[inv setTarget: self];
[inv setSelector:@selector(onTick:)];

NSTimer *t = [NSTimer timerWithTimeInterval: 1.0
                      invocation
:inv
                      repeats
:YES];

and after that, you start the timer manually whenever you need like this:

NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer: t forMode: NSDefaultRunLoopMode];



And as a note, onTick: method looks like this:

-(void)onTick:(NSTimer *)timer {
   
//do smth
}