Tuesday 25 November 2014

Removing viewcontrollers from navigation stack

Removing viewcontrollers from navigation stack :

Use this code and enjoy:

NSMutableArray *navigationArray = [[NSMutableArray alloc] initWithArray: self.navigationController.viewControllers];

// [navigationArray removeAllObjects];    // This is just for remove all view controller from navigation stack.

[navigationArray removeObjectAtIndex: 2];  // You can pass your index here
self.navigationController.viewControllers = navigationArray;

Friday 12 September 2014

Monday 18 August 2014

NSUserDefaults iPhone/Objective c

iPhone Tutorial – Saving/Retrieving Data Using NSUserDefaults :

The NSUserDefaults class provides a programmatic interface for interacting with the defaults system. The defaults system allows an application to customize its behavior to match a user’s preferences.

At runtime, you use an NSUserDefaults object to read the defaults that your application uses from a user’s defaults database. NSUserDefaults caches the information to avoid having to open the user’s defaults database each time you need a default value. The synchronize method, which is automatically invoked at periodic intervals, keeps the in-memory cache in sync with a user’s defaults database.

Saving to NSUserDefaults :
========================

Basically, all you have to do is load NSUserDefaults, and then tell it to save a value to a specific key. Here is a simple example of writing an integer to NSUserDefaults:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setInteger:101 forKey:@"RollNo"]; 
[defaults synchronize];

As mentioned earlier,
we loaded the NSUserDefaults plist to the object “defaults”. We then told that object to set an integer for the key “RollNo”.
But we know that, we must have to use “synchronize” method to save the value. It isn’t absolutely necessary, because this is called automatically every so often, but if you want to be sure to save the changes to NSUserDefaults right now, this is how.


Other Samples for NSUserDefaults :
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];     

// saving an NSString
[prefs setObject:@"IT0809" forKey:@"AccessNo"];
   
// saving an NSInteger
[prefs setInteger:42 forKey:@"RollNo"];
    

// saving a Double
[prefs setDouble:9.99 forKey:@"DoubleKey"];
    

// saving a Float
[prefs setFloat:1.7565671 forKey:@"FloatKey"];
    

[prefs synchronize];

Reading from NSUserDefaults
========================

Reading is even easier, as shown below:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger theHighScore = [defaults integerForKey:@"
RollNo"];
 
 
Other Samples for NSUserDefaults :
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// getting an NSString

NSString *myString = [prefs stringForKey:@"AccessNo"];

// getting an NSInteger

NSInteger myInt = [prefs integerForKey:@"RollNo"];

// getting an Float

float myFloat = [prefs floatForKey:@"FloatKey"];

Delete all keys from a NSUserDefaults dictionary iPhone :

- (void)resetDefaults {
     NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
     NSDictionary * dict = [defs dictionaryRepresentation];
     for (id key in dict) {
           [defs removeObjectForKey:key];
     }
     [defs synchronize];
}


Refer this Links :

  1. http://www.icodeblog.com/2008/10/03/iphone-programming-tutorial-savingretrieving-data-using-nsuserdefaults/
  2. http://ios-blog.co.uk/tutorials/quick-tips/storing-data-with-nsuserdefaults/

Thursday 31 July 2014

Common Error of iOS : 

1. xcode timed out waiting for app to launch:

Reason 1. : It turned out I was using my Distribution Profile instead of the Developer Profile in Debug mode. You can check the Profile you are using by going to Build Settings->Code Signing Entity.
Make sure you are using your Developer Profile in Beta and Debug mode.

Reason 2. : I had this problem when I used a Distribution certificate instead of Developer one when running the app from Xcode. You may check it out your target --> Build Settings --> Code signing.

Check Below Links:

Tuesday 29 July 2014

UIWebView in Objective C :

Loading Request in Webview

To load a request you can use the below methods.

1. requestWithURL is used to load a URL in Webview


NSMutableURLRequest * request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]];
[webview loadRequest:request];

2. loadHTMLString is used load HTML string in UIWebView
You can use the below code to load HTML string in webview



NSString * string = @"<html><body><h1>Hayageek</h1>How to <a href=\"/add-custom-fonts-ios/\">Add Custom Font</a>";
[webview loadHTMLString:string baseURL:[NSURL URLWithString:@"http://hayageek.com"]];

3. loadData method is used to Load NSData in webview. Documents like .doc,.pdf,.xls,.txt,…etc are opened with UIWebview.



NSString * path =[[NSBundle mainBundle] pathForResource:@"Resume" ofType:@"doc"];
NSData *data =[[NSFileManager defaultManager] contentsAtPath:path];

[webview loadData:data MIMEType:@"application/msword" textEncodingName:@"UTF-8"baseURL:nil];

To get the list of MIME types:http://webdesign.about.com/od/multimedia/a/mime-types-by-content-type.htm

UIWebViewDelegate methods.

In order to get UIWebViewDelegate callbacks, you need to add UIWebViewDelegate protocol to your class and set the webview delegate class.

ViewController.h Source:

@interface ViewController : UIViewController<UIWebViewDelegate>{
}
@property (weak, nonatomic) IBOutlet UIWebView *webview;
@end

 








ViewController.m Source:

@implementation ViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    [webview setDelegate:self];
}
@end
 


UIWebViewDelegate has the following delegate methods.

 webView:shouldStartLoadWithRequest:navigationType: method is called before loading a frame. If the method returns YES, request is loaded. Otherwise NO.
Using this method, requests can be filtered.

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
   NSLog(@"Loading URL :%@",request.URL.absoluteString);

    //return FALSE; //to stop loading
    return YES;
}






Filtering Clicks, Form Submission,Ads:

//To avoid link clicking.
if(navigationType ==UIWebViewNavigationTypeLinkClicked)
return  NO;

//To avoid form submission.
if(navigationType ==UIWebViewNavigationTypeFormSubmitted)
return  NO;

//To avoid loading all the google ads.
if([request.URL.absoluteString rangeOfString:@"googleads"].location != NSNotFound)
    return NO;





webViewDidStartLoad method is called when a frame starts loading.
- (void)webViewDidStartLoad:(UIWebView *)webView
{

}



webViewDidFinishLoad method is called when a frame finishes loading.
- (void)webViewDidStartLoad:(UIWebView *)webView
{

}





webView:didFailLoadWithError: method is called if frame loading is failed.
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    NSLog(@"Failed to load with error :%@",[error debugDescription]);

}




Execute JavaScript in UIWebview.

You can execute javascript programmatically in WebView using the method stringByEvaluatingJavaScriptFromString.
Examples:
//Show Cookie as alert in WebView
[webview stringByEvaluatingJavaScriptFromString:@"alert(document.cookie)"];

//Get Cookie
NSString * cookie=[webview stringByEvaluatingJavaScriptFromString:@"document.cookie"];
NSLog(@"cookie =%@",cookie);

//Get sum of 2+3
NSString * result1 =[webview stringByEvaluatingJavaScriptFromString:@"2+3"];
NSLog(@"2+3:%ld",(long)[result1 integerValue]);

//Redirect the current page in WebView
[webview stringByEvaluatingJavaScriptFromString:@"location.href=\"http://apple.com\""];
 



4).How to add a UIWebview to View Programmatically

UIWebview is added to a View programmatically using the below code.

- (void)viewDidLoad
{
    [super viewDidLoad];

    //set desired width and height
    UIWebView *myWebView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 100, 300, 300)];
    [myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]]];
    [self.view addSubview:myWebView];

}



Wednesday 9 July 2014

Dotted line border around UIView:

Its a Very Easy..

[yourView.layer setBorderWidth:5.0]; 
 
///just add image name and create image with dashed or doted drawing and add here 
[yourView.layer setBorderColor:[[UIColor colorWithPatternImage:
                [UIImage imageNamed:@"DotedImage.png"]] CGColor]]; 

Here, 
1. You just required add QuartzCore/QuartzCore.h Framework in project and 
2. import it like bellow in .m file
  #import <QuartzCore/QuartzCore.h>
 
Hope this help you...

 

Tuesday 17 June 2014

Asynchronous Operations in iOS with Grand Central Dispatch

Grand Central Dispatch, or GCD for short, is a C API that makes it exceptionally easy to perform asynchronous operations in iOS. Asynchronous operations are a fundamental part of every iOS app when you want to perform long operations without freezing or blocking the user interface. You can image that if your entire app froze without warning then your users would get quite irritated.
With GCD, you can line up blocks of code in a queue for the system to execute as necessary. These blocks or operations, will be dispatched in the queue to another thread, leaving your main UI thread to continue its tasks. It’s important to know that GCD will use separate threads for it’s operations but which thread it isn’t important to you. All that matters is that your long running process in a separate thread outside the main thread where your UI and gestures are running.

GCD queues can be concurrent or serial but serial queues (where there is one queue and each item is executed one after the other in order) are easier to understand so we’ll look at those.
The more important functions you’ll need are for creating the queue:

dispatch_queue_t dispatch_queue_create(const char *label, dispatch_queue_attr_t attr);
and adding blocks to the queue:

void dispatch_async(dispatch_queue_t queue, dispatch_block_t block);
 
There’s also a couple helper functions for retrieving specific queues such as:
dispatch_queue_t dispatch_get_current_queue(void);
dispatch_queue_t dispatch_get_main_queue(void);
 
The dispatch_get_current_queue function will return the current queue from which the block is dispatched and the dispatch_get_main_queue function will return the main queue where your UI is running.

The dispatch_get_main_queue function is very useful for updating the iOS app’s UI as UIKit methods are not thread safe (with a few exceptions) so any calls you make to update UI elements must always be done from the main queue.

A typical GCD call would look something like this:
// Doing something on the main thread

dispatch_queue_t myQueue = dispatch_queue_create("My Queue",NULL);
dispatch_async(myQueue, ^{
    // Perform long running process
    
    dispatch_async(dispatch_get_main_queue(), ^{
        // Update the UI
        
    });
}); 

// Continue doing other stuff on the 
// main thread while process is running.
GCD relies on block so it has a really nice, readable syntax. It becomes clear what happes in the background thread and the main thread. For example, here’s how you might load a few images:
NSArray *images = @[@"http://example.com/image1.png",
                 @"http://example.com/image2.png",
                 @"http://example.com/image3.png",
                 @"http://example.com/image4.png"];

dispatch_queue_t imageQueue = dispatch_queue_create("Image Queue",NULL);

for (NSString *urlString in images) {
    dispatch_async(imageQueue, ^{
        
        NSURL *url = [NSURL URLWithString:urlString];
        NSData *imageData = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:imageData];

        NSUInteger imageIndex = [images indexOfObject:urlString];
        UIImageView *imageVIew = (UIImageView *)[self.view viewWithTag:imageIndex];
        
        if (!imageView) return;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            // Update the UI
            [imageVIew setImage:image];
        });
        
    }); 
}

// Continue doing other stuff while images load.
 
You’ll notice I check for imageView before dispatching to the main thread. This avoids the main queue dispatch if the network request took a long time and the imageView is no longer there for one reason or another. Once a block has been dispatched onto a queue, it’s not possible to stop it. The block will execute to completion and there’s nothing you can do. If you have a very long running process, such as loading a URL, you should add logic between each step to check to see if it should continue and if it’s still appropriate to finish the operation.
That’s it. Start build queues and making your UI more responsive.

Aside: Concurrency

If you want to run a single independent queued operation and you’re not concerned with other concurrent operations, you can use the global concurrent queue:
dispatch_queue_t globalConcurrentQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
This will return a concurrent queue with the given priority as outlined in the documentation:
DISPATCH_QUEUE_PRIORITY_HIGH Items dispatched to the queue will run at high priority, i.e. the queue will be scheduled for execution before any default priority or low priority queue.
DISPATCH_QUEUE_PRIORITY_DEFAULT Items dispatched to the queue will run at the default priority, i.e. the queue will be scheduled for execution after all high priority queues have been scheduled, but before any low priority queues have been scheduled.
DISPATCH_QUEUE_PRIORITY_LOW Items dispatched to the queue will run at low priority, i.e. the queue will be scheduled for execution after all default priority and high priority queues have been scheduled.
DISPATCH_QUEUE_PRIORITY_BACKGROUND Items dispatched to the queue will run at background priority, i.e. the queue will be scheduled for execution after all higher priority queues have been scheduled and the system will run items on this queue on a thread with background status as per setpriority(2) (i.e. disk I/O is throttled and the thread’s scheduling priority is set to lowest value).
from queue.h

 

Friday 13 June 2014

How to find iPhone UDID in iphone 5, 5C & 5S iOS7 : 

What is the UDID?

Each iPhone or iPod Touch has a Unique Device Identifier (UDID), which is a sequence of 40 letters and numbers that is specific to your device. It’s like a serial number but much harder to guess. Apple has hidden the UDID from all public APIs, starting with iOS 7. Any UDID that begins with FFFF is a fake ID. The "Send UDID" apps that previously worked can no longer be used to gather UDID for test devices.

How do I get my UDID?

Easy Way .. Copy/Paste from iTunes
  1. Launch iTunes and connect your iPhone.
  2. In the right pane, locate the information about your iPhone, including its name, capacity, software version, serial number, and phone number.
  3. Reveal the Identifier by clicking on Serial Number:. Copy the Identifier to your clipboard by choosing Edit → Copy.

More Easy ? UDID app !!

There are a number of free apps that will tell you the UDID for your iOS device.
  1. http://whatsmyudid.com
  2. http://get.udid.io Wait..

Are you an iOS developer ? Well try this..

UDID is no longer available in iOS 6+ due to security / privacy reasons. Instead, use identifierForVendor or advertisingIdentifier.


identifierForVendor: An alphanumeric string that uniquely identifies a device to the app’s vendor. (read-only) The value of this property is the same for apps that come from the same vendor running on the same device. A different value is returned for apps on the same device that come from different vendors, and for apps on different devices regardless of vendor.

You can use identifierForVendor after that store them to keychain and use later. Because value of keychain will not changed when re-install app.


advertisingIdentifier: An alphanumeric string unique to each device, used only for serving advertisements. (read-only) Unlike the identifierForVendor property of UIDevice, the same value is returned to all vendors. This identifier may change—for example, if the user erases the device—so you should not cache it.

Check out OpenUDID: Open source initiative for a universal and persistent UDID solution for iOS http://OpenUDID.org

OpenUDID is a drop-in replacement for the deprecated uniqueIdentifier property of the UIDevice class on iOS (a.k.a. UDID) and otherwise is an industry-friendly equivalent for iOS and Android, and most recently Windows C# and Silverlight (see links above).
Also We can use identifierForVendor for ios7,

-(NSString*)uniqueIDForDevice
{
    NSString* uniqueIdentifier = nil;
// >=iOS 7 
if( [UIDevice instancesRespondToSelector:@selector(identifierForVendor)] ){
        uniqueIdentifier = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    } else { //<=iOS6, Use UDID of Device       
            CFUUIDRef uuid = CFUUIDCreate(NULL);
            //- for non- ARC
            //uniqueIdentifier = ( NSString*)CFUUIDCreateString(NULL, uuid);
            // for ARC
            uniqueIdentifier = ( NSString*)CFBridgingRelease(CFUUIDCreateString(NULL, 
                                uuid));
            CFRelease(uuid);
         }
    }
return uniqueIdentifier;
}

 

Wednesday 11 June 2014

What is .cer, .pem, .key file?


SSL has been around for long enough you'd think that there would be agreed upon container formats. And you're right, there are. Too many standards as it happens. So this is what I know, and I'm sure others will chime in.
  • .csr This is a Certificate Signing Request. Some applications can generate these for submission to certificate-authorities. It includes some/all of the key details of the requested certificate such as subject, organization, state, whatnot, as well as the public key of the certificate to get signed. These get signed by the CA and a certificate is returned. The returned certificate is the public certificate, which itself can be in a couple of formats.
  • .pem Defined in RFC's 1421 through 1424, this is a container format that may include just the public certificate (such as with Apache installs, and CA certificate files /etc/ssl/certs), or may include an entire certificate chain including public key, private key, and root certificates. The name is from Privacy Enhanced Email, a failed method for secure email but the container format it used lives on.
  • .key This is a PEM formatted file containing just the private-key of a specific certificate. In Apache installs, this frequently resides in /etc/ssl/private. The rights on this directory and the certificates is very important, and some programs will refuse to load these certificates if they are set wrong.
  • .pkcs12 .pfx .p12 Originally defined by RSA in the Public-Key Cryptography Standards, the "12" variant was enhanced by Microsoft. This is a passworded container format that contains both public and private certificate pairs. Unlike .pem files, this container is fully encrypted. Every time I get one I have to google to remember the openssl-fu required to break it into .key and .pem files.
A few other formats that show up from time to time:
  • .der A way to encode ASN.1 syntax, a .pem file is just a Base64 encoded .der file. OpenSSL can convert these to .pem. Windows sees these as Certificate files. I've only ever run into them in the wild with Novell's eDirectory certificate authority.
  • .cert .cer A .pem formatted file with a different extension, one that is recognized by Windows Explorer as a certificate, which .pem is not.
  • .crl A certificate revocation list. Certificate Authorities produce these as a way to de-authorize certificates before expiration.

In summary, there are three different ways to present certificates and their components:
  • PEM Governed by RFCs, it's used preferentially by open-source software. It can have a variety of extensions (.pem, .key, .cer, .cert, more)
  • PKCS12 A private standard that provides enhanced security versus the plain-text PEM format. It's used preferentially by Windows systems, and can be freely converted to PEM format through use of openssl.
  • DER The parent format of PEM. It's useful to think of it as a binary version of the base64-encoded PEM file. Not routinely used by anything in common usage.
I hope this helps.

Monday 9 June 2014

Combine one UIImage onto of another UIImage : 

Check the Full Sample From Here : Sample Code

Combining two images, especially useful, if the overlay image has an alpha value:

 
#import <Foundation/Foundation.h> 
 
@interface UIImage (combine)
- (UIImage*)overlayWith:(UIImage*)overlayImage;
@end
 
 
And the implementation file.

#import "UIImage+Category.h" 
 
@implementation UIImage (combine)
 
- (UIImage*)overlayWith:(UIImage*)overlayImage {
   UIGraphicsBeginImageContext(self.size);
   [self drawAtPoint:CGPointZero];
   [overlayImage drawAtPoint:CGPointZero];
   UIImage *combinedImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();
   return combinedImage;
}
 
@end
 

Above i have declare the UIImage+Category Lib files for the UIImage.

You can see the below sample Example for calling the method for combining
the one image to another and set both images to one images.

You can combine multiple images using this methods.:
#import "ViewController.h"
#import "UIImage+Overlay.h"

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.theImageView.image = [self mergingImage];
}

-(UIImage *)mergingImage {
    UIImage *background = [UIImage imageNamed:@"background.png"];
    UIImage *audiImage = [UIImage imageNamed:@"audi.png"];
    UIImage *combineImage = [background overlayWith:audiImage];
    return combineImage;
}
 
You can Download Transparent images from Here : images.zip 
Output of the Project : 







audi.png
 
 
 
Background.png

 
 


       +
 
 
 
 
 
Combine image
 

Friday 6 June 2014

Delete All Files in Documents Directory


The first approach I took was to loop through all the files, building a path to each, one by one:

  1. // Path to the Documents directory
  2. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  3. if ([paths count] > 0)
  4. {
  5.   NSError *error = nil;  
  6.   NSFileManager *fileManager = [NSFileManager defaultManager];
  7.  
  8.   // Print out the path to verify we are in the right place
  9.   NSString *directory = [paths objectAtIndex:0];
  10.   NSLog(@"Directory: %@", directory);
  11.  
  12.   // For each file in the directory, create full path and delete the file
  13.   for (NSString *file in [fileManager contentsOfDirectoryAtPath:directory error:&error])
  14.   {    
  15.     NSString *filePath = [directory stringByAppendingPathComponent:file];
  16.     NSLog(@"File : %@", filePath);
  17.  
  18.     BOOL fileDeleted = [fileManager removeItemAtPath:filePath error:&error];
  19.  
  20.     if (fileDeleted != YES || error != nil)
  21.     {
  22.       // Deal with the error...
  23.     }
  24.   }
  25.  
  26. }

 The code above works fine, however, I was interested in something that didn’t build each path separately – the code below deletes all the files in one fell swoop:

  1. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  2. if ([paths count] > 0)
  3. {
  4.   NSLog(@"Path: %@", [paths objectAtIndex:0]);
  5.  
  6.   NSError *error = nil;  
  7.   NSFileManager *fileManager = [NSFileManager defaultManager];
  8.  
  9.   // Remove Documents directory and all the files
  10.   BOOL deleted = [fileManager removeItemAtPath:[paths objectAtIndex:0] error:&error];
  11.  
  12.   if (deleted != YES || error != nil)
  13.   {
  14.     // Deal with the error...
  15.   }
  16.  
Given the requested item to remove was a directory, as you’d expect, not only were the files deleted, so was the Documents directory. Problem is, I ran into errors when I attempted to drag/drop new files into the file sharing areas iTunes.
To get things working again, I changed up the code above to create the Documents directory:

  1. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  2. if ([paths count] > 0)
  3. {
  4.   NSLog(@"Path: %@", [paths objectAtIndex:0]);
  5.  
  6.   NSError *error = nil;  
  7.   NSFileManager *fileManager = [NSFileManager defaultManager];
  8.  
  9.   // Remove all files in the documents directory
  10.   BOOL deleted = [fileManager removeItemAtPath:[paths objectAtIndex:0] error:&error];
  11.  
  12.   if (deleted != YES || error != nil)
  13.   {
  14.     // Deal with the error...
  15.   }
  16.   else
  17.     // Recreate the Documents directory
  18.     [fileManager createDirectoryAtPath:[paths objectAtIndex:0] withIntermediateDirectories:NO attributes:nil error:&error];
  19.  
  20. }
 Although there is less code to delete the Documents directory, something tells me it may simply be a better (and more robust) solution to loop and delete each file in sequence.

Wednesday 4 June 2014

Save and Load UIImage in Documents directory on iPhone:

The following function saves UIImage in test.png file in the user Document folder:


- (void)saveImage: (UIImage*)image
{
    if (image != nil)
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                      NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString* path = [documentsDirectory stringByAppendingPathComponent: 
                       [NSString stringWithString: @"test.png"] ];
        NSData* data = UIImagePNGRepresentation(image);
        [data writeToFile:path atomically:YES];
    }
} 
 

The following function loads UIImage from the test.png file:

- (UIImage*)loadImage { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString* path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithString: @"test.png"] ]; UIImage* image = [UIImage imageWithContentsOfFile:path]; return image; }

Change UITextField’s placeholder color without subclassing it

Reference URL :
1. http://stackoverflow.com/questions/1340224/iphone-uitextfield-change-placeholder-text-color

The safe way to customize UITextField’s placeholder is subclassing the UITextField and overriding placeholderRectForBounds:, Apple won’t bother you on this one. However, if you want to take the risk, you can try this way:
[self.MyTextField setValue:[UIColor darkGrayColor] forKeyPath:@"_placeholderLabel.textColor"];


if ([textField respondsToSelector:@selector(setAttributedPlaceholder:)]) {
  UIColor *color = [UIColor blackColor];
  textField.attributedPlaceholder = [[NSAttributedString alloc] 
         initWithString:placeholderText 
         attributes:@{NSForegroundColorAttributeName: color}];
} else {
  NSLog(@"Cannot set placeholder text's color, because 
            deployment target is earlier than iOS 6.0");
  // TODO: Add fall-back code to set placeholder color.
}

Tuesday 29 April 2014

Getting the NSFileManager Reference:

I followed the Below Blog:

First we need to recap the steps necessary to obtain a reference to creatane an instance of the NSFileManager class. As discussed in the previous chapter, the NSFileManager class contains a class method named defaultManager that is used to create an instance of the class. For example:obtain a reference to the NSFileManager object instance:
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];

Checking if a File Exists

The NSFileManager class contains an instance method named fileExistsAtPath that checks whether a specified file already exists. The method takes as an argument an NSString object containing the path to file and returns a boolean YES or NO value indicating the presence or otherwise of that file:
NSFileManager *filemgr;

filemgr = [NSFileManager defaultManager];

if ([filemgr fileExistsAtPath: @"/tmp/myfile.txt" ] == YES)
        NSLog (@"File exists");
else
        NSLog (@"File not found");

Comparing the Contents of Two Files

The contents of two files can be compared for equality using the contentsEqualAtPath method. This method takes as arguments the paths to the two files to be compared and returns a boolean YES or NO to indicate whether the file contents match:
NSFileManager *filemgr;

filemgr = [NSFileManager defaultManager];

if ([filemgr contentsEqualAtPath: @"/tmp/myfile.txt" andPath: @"/tmp/sales.txt"] == YES)
        NSLog (@"File contents match");
else
        NSLog (@"File contents do not match");

Checking if a File is Readable/Writable/Executable/Deletable

Most operating systems provide some level of file access control. These typically take the form of attributes that control the level of access to a file for each user or user group. As such, it is not a certainty that your program will have read or write access to a particular file, or the appropriate permissions to delete or execute it. The quickest way to find out if your program has a particular access permission is to use the isReadableFileAtPath, isWritableFileAtPath, isExecutableFileAtPath and isDeletableFileAtPath methods. Each method takes a single argument in the form of the path to the file to be checked and returns a boolean YES or NO result. For example, the following code excerpt checks to find out if a file is writable:
NSFileManager *filemgr;

filemgr = [NSFileManager defaultManager];

if ([filemgr isWritableFileAtPath: @"/tmp/myfile.txt"]  == YES)
        NSLog (@"File is writable");
else
        NSLog (@"File is read only");
To check for other access permissions simply substitute the corresponding method name in place of isWritableFileAtPath in this example.

Moving/Renaming a File

A file may be renamed (assuming adequate permissions) using the moveItemAtURL method. This method returns a boolean YES or NO result and takes as arguments the pathname for the file to be moved, the destination path and an optional NSError object into which information describing any errors encountered during the operation will be placed. If no error description information is required, this argument may be set to NULL. Note that if the destination file path already exists this operation will fail.
NSFileManager *filemgr;

filemgr = [NSFileManager defaultManager];

NSURL *oldPath = [NSURL fileURLWithPath:@"/tmp/myfile.txt"];
NSURL *newPath= [NSURL fileURLWithPath:@"/tmp/newfile.txt"];

[filemgr moveItemAtURL: oldPath toURL: newPath error: nil];

Copying a File

File copying can be achieved using the copyItemAtPath method. As with the move method, this takes as arguments the source and destination pathnames and an optional NSError object. Success of the operation is indicated by the returned boolean value:
NSFileManager *filemgr;

filemgr = [NSFileManager defaultManager];

if ([filemgr copyItemAtPath: @"/tmp/myfile.txt" toPath: @"/Users/demo/newfile.txt" error: NULL]  == YES)
        NSLog (@"Copy successful");
else
        NSLog (@"Copy failed");


Removing a File

The removeItemAtPath method removes the specified file from the file system. The method takes as arguments the pathname of the file to be removed and an optional NSError object. The success of the operation is, as usual, reported in the form of a boolean YES or NO return value:
NSFileManager *filemgr;

filemgr = [NSFileManager defaultManager];

if ([filemgr removeItemAtPath: @"/tmp/myfile.txt" error: NULL]  == YES)
        NSLog (@"Remove successful");
else
        NSLog (@"Remove failed");

Creating a Symbolic Link

A symbolic link to a particular file may be created using the createSymbolicLinkAtPath method. This takes as arguments the path of the symbolic link, the path to the file to which the link is to refer and an optional NSError object. For example, the following code creates a symbolic link from/tmpUsers/demo/myfile21.txt that links to the pre-existing file /tmp/myfile.txt:
NSFileManager *filemgr;

filemgr = [NSFileManager defaultManager];

if ([filemgr createSymbolicLinkAtPath: @"/tmp/myfile2.txt"
                withDestinationPath: @"/tmp/myfile.txt" error: NULL] == YES)
        NSLog (@"Link successful");
else
        NSLog (@"Link failed");NSFileManager *filemgr;

filemgr = [NSFileManager defaultManager];

if ([filemgr createSymbolicLinkAtPath: @"/Users/demo/file1.txt" 
                withDestinationPath: @"/tmp/myfile.txt" error: NULL] == YES)
        NSLog (@"Remove successful");
else
        NSLog (@"Remove failed");

Reading and Writing Files with NSFileManager

The NSFileManager class includes some basic file reading and writing capabilities. these capabilities are somewhat limited when compared to the options provided by the NSFileHandle class, but can be useful nonetheless.
Firstly, the contents of a file may be read and stored in an NSData object through the use of the contentsAtPath method:
NSFileManager *filemgr;
NSData *databuffer;

filemgr = [NSFileManager defaultManager];

databuffer = [filemgr contentsAtPath: @"/tmp/myfile.txt" ];
Having stored the contents of a file in an NSData object, that data may subsequently be written out to a new file using the createFileAtPath method:
databuffer = [filemgr contentsAtPath: @"/tmp/myfile.txt" ];

[filemgr createFileAtPath: @"/tmp/newfile.txt" contents: databuffer attributes: nil];




In the above example we have essentially copied the contents from an existing file to a new file. This, however, gives us no control over how much data is to be read or written and does not allow us to append data to the end of an existing file. If the file /tmp/newfile.txt in the above example had already existed it, and any data it contained, would have been overwritten by the contents of the source file. Clearly some more flexible mechanism is required. This is provided by the Foundation Framework in the form of the NSFileHandle class.

Working with Files using the NSFileHandle Class

The NSFileHandle class provides a range of methods designed to provide a more advanced mechanism for working with files. In addition to files, this class can also be used for working with devices and network sockets. In the following sections we will look at some of the more common uses for this class.

Creating an NSFileHandle Object

An NSFileHandle object can be created when opening a file for reading, writing or updating (reading and writing). This is achieved using the fileHandleForReadingAtPath, fileHandleForWritingAtPath and fileHandleForUpdatingAtPath methods respectively. Having opened a file, it must subsequently be closed when we have finished working with it using the closeFile method. If an attempt to open a file fails, for example because an attempt is made to open a non-existent file for reading, these methods return nil.
For example, the following code excerpt opens a file for reading and writing and then closes it without actually doing anything to the file:
NSFileHandle *file;

file = [NSFileHandle fileHandleForWritingAtPath: @"/tmp/myfile.txt"];

if (file == nil)
        NSLog(@"Failed to open file");

[file closeFile];

NSFileHandle File Offsets and Seeking

NSFileHandle objects maintain a pointer to the current position in a file. This is referred to as the offset. When a file is first opened the offset is set to 0 (the beginning of the file). This means that any read or write operations we perform using the NSFileHandle methods will take place at offset 0 in the file. To perform operations at different locations in a file (for example to append data to the end of the file) it is first necessary to seek to the required offset. For example to move the current offset to the end of the file, use the seekToEndOfFile method. Alternatively, seekToFileOffset allows you to specify the precise location in the file to which the offset is to be positioned. Finally, the current offset may be identified using the offsetInFile method. In order to accommodate large files, the offset is stored in the form of an unsigned long long.
The following example opens a file for reading and then performs a number of method calls to move the offset to different positions, outputting the current offset after each move:
NSFileHandle *file;

file = [NSFileHandle fileHandleForUpdatingAtPath: @"/tmp/myfile.txt"];

if (file == nil)
        NSLog(@"Failed to open file");

NSLog (@"Offset = %llu", [file offsetInFile]);

[file seekToEndOfFile];

NSLog (@"Offset = %llu", [file offsetInFile]);

[file seekToFileOffset: 30];

NSLog (@"Offset = %llu", [file offsetInFile]);

[file closeFile];
File offsets are a key aspect of working with files using the NSFileHandle class so it is worth taking extra time to make sure you understand the concept. Without knowing where the current offset is in a file it is impossible to know where in the file data will be read or written.

Reading Data from a File

Once a file has been opened and assigned a file handle, the contents of that file may be read from the current offset position. The readDataOfLength method reads a specified number of bytes of data from the file starting at the current offset. For example, the following code reads 5 bytes of data from offset 10 in a file. The data read is returned encapsulated in an NSData object:
NSFileHandle *file;
NSData *databuffer;

file = [NSFileHandle fileHandleForReadingAtPath: @"/tmp/myfile.txt"];

if (file == nil)
        NSLog(@"Failed to open file");

[file seekToFileOffset: 10];

databuffer = [file readDataOfLength: 5];

[file closeFile];
Alternatively, the readDataToEndOfFile method will read all the data in the file starting at the current offset and ending at the end of the file.

Writing Data to a File

The writeData method writes the data contained in an NSData object to the file starting at the location of the offset. Note that this does not insert data but rather overwrites any existing data in the file at the corresponding location.
To see this in action we need to begin with a file. Using a text editor, create a file named quickfox.txt, enter the following text and save it in the /tmp directory:
The quick brown fox jumped over the lazy dog
Next, we will write a program that opens the file for updating, seeks to position 10 and then writes some data at that location:
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
    @autoreleasepool {

        NSFileHandle *file;
        NSMutableData *data;

        const char *bytestring = "black dog";

        data = [NSMutableData dataWithBytes:bytestring length:strlen(bytestring)];


        file = [NSFileHandle fileHandleForUpdatingAtPath: @"/tmp/quickfox.txt"];

        if (file == nil)
                NSLog(@"Failed to open file");


        [file seekToFileOffset: 10];

        [file writeData: data];

        [file closeFile];

    }
    return 0;
}
When the above program is compiled and executed the contents of the quickfox.txt will have changed to:
The quick black dog jumped over the lazy dog

Truncating a File

A file may be truncated at the specified offset using the truncateFileAtOffset method. To delete the entire contents of a file, specify an offset of 0 when calling this method:
        NSFileHandle *file;

        file = [NSFileHandle fileHandleForUpdatingAtPath: @"/tmp/quickfox.txt"];

        if (file == nil)
                NSLog(@"Failed to open file");

        [file truncateFileAtOffset: 0];

        [file closeFile];