Sunday, 13 March 2011

Documents Directory File Path - iPhone, iPad, iOS Development

Getting the file path to the documents directory is very simple however the documentation in this area can be rather confusing.

Firstly you call the function NSSearchPathForDirectoriesInDomains(). This function returns an array however there will almost always only be one object within the array.

 NSArray * NSSearchPathForDirectoriesInDomains (  NSSearchPathDirectory directory,  NSSearchPathDomainMask domainMask,  BOOL expandTilde );

The reference for the method is shown above.
The Directory value must be one of the predefined search path directories of the operating system. The most commonly used directory and the one we'll use here is the documents directory which the value for is NSDocumentDirectory.  
Other values can be seen in the documentation here.
The domain mask value is most often NSUserDomainMask meaning the returned path is local to the user's home directory.  Other possible values are shown below.
 NSUserDomainMask - Local to the user's home directory.
 NSLocalDomainMask - local to the current machine.
 NSNetworkDomainMask - Publicly available location in the local area network.
 NSSystemDomainMask - /System (Usually unused private).
 NSAllDomainsMask - will return a path for each of the above domains.
The full example of how to obtain a string of the system file path to the user documents directory is shown below.
 -(NSString *)documentsDirectoryPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
return documentsDirectoryPath;
}

Hide Keyboard on Text Field Return - iPhone, iPad, iOS Development

One of the most asked question's by new iPhone developers is how to hide the keyboard. This is certainly one of the most lacking area's of the documentation for a budding iPhone developer.

To programatically hide the keyboard you must call the method resignFirstResponder on your text field or text view. This can be called from anywhere however it is most commonly from a done button or from the keyboard return key being pressed.
  [textField resignFirstResponder];
To hide the keyboard when the return key is pressed you must add a listener to the text field (UITextField) delegate method. UITextfieldDelegate protocol contains a method called textFieldShouldReturn, This method is called to determine if the text field should process the pressing of the return key. You can call your resignFirstResponder on the text field from within this method to hide the keyboard when pressed.

 - (BOOL)textFieldShouldReturn:(UITextField *)textField {
[
textField resignFirstResponder];
}


If this doesn't appear to be working for you make sure you've remembered to set the delegate property on the textField.

If you have any problems feel free to post in the comment's ;)