Thursday, July 31, 2014

iphone: reading file and loading data into textview

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"about" ofType:@"txt"];
if (filePath) {
    NSString *content = [NSString stringWithContentsOfFile:filePath];
if (content) {

    textView.text= content;
}


For loading HTML data into file
 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"about" ofType:@"html"];
    if (filePath) {
        NSString *content = [NSString stringWithContentsOfFile:filePath];
        if (content) {
             NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[content dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
           textView.attributedText = attributedString;
        }
        
    }

Friday, July 18, 2014

Iphone: UIAlert with message box

 UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Hello Cogi User!" message:@"Please enter phone number of this device:" delegate:self cancelButtonTitle:@"Continue" otherButtonTitles:nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    UITextField * alertTextField = [alert textFieldAtIndex:0];
    alertTextField.keyboardType = UIKeyboardTypeNumberPad;
    alertTextField.placeholder = @"Enter Phone Number";

    [alert show];


-------
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSString* detailString =[alertView textFieldAtIndex:0].text;
   
    
   
    if (buttonIndex == 0){
        
     // do your work
        
        return; //If cancel or 0 length string the string doesn't matter
    }
   
}

Iphone: UIButton with rounded corner

-(void)setButtonStyling:(UIButton *)button
{
    CALayer *layer = [button layer];
    [layer setCornerRadius:5.0f];
    [layer setMasksToBounds:YES];
    [layer setBorderWidth:1.0f];
    [layer setBorderColor:[[UIColor colorWithWhite:0.4f alpha:0.2f] CGColor]];

}


//setting and calling the function
 [self setButtonStyling:self.myButton];
   

Monday, July 14, 2014

Friday, July 11, 2014

Iphone: UIButton text setting - wrong and correct way

Wrong way:
       self.notificationButton.titleLabel.text=[NSString stringWithFormat:@"%i",notificationCount];
Correct way:
        [self.notificationButton setTitle:[NSString stringWithFormat:@"%i",notificationCount] forState:UIControlStateNormal];


By setting in a wrong way, title changed to default (set using storyboard) when user will click

Iphone: Core data (database) versioning

Solution is copied from the link

Migrating what and when?

I only use migrations and version models when an application is already used in production. Core Data will not automatically update its database when you change something in it. The app will just crash... And I don't think that's what the user wants. The app won't always crash: sometimes the changes just aren't executed and there will occur a problem when you try to call a method related to the changes.

A new version

Go to Editor > Model Version in order to create a new version of your Core Data Model. Choose a name and select the Model you want to use as the starting point, this will be the database you currently use in the production app.
A new version
Now that we've created a new version we can just apply some changes to it. It's just a copy of our old xcdatamodel file.
The last thing we have to do is set this version of the Core Data Model as our default version. In your project navigator select the .xcdatamodeld container in which the 2 versions reside. Open the Utilities pane on the left and select the File Inspector. Here you can change your Current version of your model.
Set the default version

Simple mapping

The mapping model is the place where you tell Core Data how to handle model changes between 2 versions. You don't always need a mapping model, when you add or remove a column/model for example. But when you want to do more complex migrations like renaming a column or filling the added columns with new values, then this is the way to go.
Add a new "Mapping Model" file to your project, and follow the steps to complete the creation.
Create a mapping model
In this model you can see all the Entity Mappings with the changes between the 2 versions.
Here is an example on how you rename a field (name to fullName) and connect the data between the 2 Core Data Models:
The mapping
After the migration the field will be renamed, and the data will be preserved.

Custom mapping

When we want to do a bit more advanced mapping, we'll have to subclass NSEntityMigrationPolicy in order to get the result we want.
In the next example we will autofill the newly added field (companyName) with a default value '10to1'.
Create a new file called CustomPhotoMigration that subclasses fromNSEntityMigrationPolicy and add the following code to the implementation class. You can choose the name of the file, doesn't really matter.
- (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)instance
                                      entityMapping:(NSEntityMapping *)mapping
                                            manager:(NSMigrationManager *)manager
                                              error:(NSError **)error {
    NSArray *_properties = [mapping attributeMappings];
    for (NSPropertyMapping *_property in _properties) {
        if ([[_property name] isEqualToString:@"companyName"]) {
            NSExpression *_expression = [NSExpression expressionForConstantValue:@"10to1"];
            [_property setValueExpression:_expression];
        }
    }
    
    return [super createDestinationInstancesForSourceInstance:instance 
                                                entityMapping:mapping 
                                                      manager:manager 
                                                        error:error];
}
Once the file is created you'll have to tell the mapping model to use our custom policy. Go to your .xcmappingmodel file and click on the entity mapping you would like to customize. In the Mapping Model Inspector pane on the right, just fill in the class name of your custom policy. In our case this will be CustomPhotoMigration.
The custom mapping policy
This should auto fill the companyName field on every existing record with "10to1" the next time you run the app.
For the record: you don't have to run a script or something like that to perform the migration. Just run your application and it will be executed for you.

    Thursday, July 10, 2014

    iphone: searching in a character separated string

    // example is for comma separated string

    BOOL found=NO;

    NSString * originalString="abc,cde,efg",
        NSArray * mystrings=[originalString componentsSeparatedByString:@","];
        
        for(NSString *i in mystrings){
            NSLog(i);
            if ([i isEqualToString:@"cde"]) {
                found=YES;
                break;
            }
            

        }

    Wednesday, July 9, 2014

    Iphone: validating string with length minimum 6 characters and having atleast one number

    -(BOOL)validatePass:(NSString *)passString{
        if (passString.length >=6) {
            
            NSString *str =passString; // some string to check for at least one digit and a length of at least 7
            if ([str rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]].location != NSNotFound) {
                // this matches the criteria
                return YES;
            }
            else
            {
               return NO;
            }
            
            
            
            
        }
        else{
            return NO;
        }

    }

    Monday, July 7, 2014

    IPhone: Separating the functions for fast access

    user #pragma mark
    link

    Iphone: Tap Gesture recognizer on a view

    UITapGestureRecognizer *tapGR;
    tapGR = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)] autorelease];
    tapGR.numberOfTapsRequired = 1;
    [myUIView addGestureRecognizer:tapGR];
    
    // Add a delegate method to handle the tap and do something with it.
    -(void)handleTap:(UITapGestureRecognizer *)sender
    {
        if (sender.state == UIGestureRecognizerStateEnded) {
            // handling code
        }
    }

    Wednesday, July 2, 2014

    IPhone: Email validation

    - (BOOL) validateEmail: (NSString *) candidate 
    {
        NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; 
        NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; 
    
        return [emailTest evaluateWithObject:candidate];
    }

    Tuesday, July 1, 2014

    IPhone: UIView animation


    Before any change
     [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.2]; 


    after the change

     [UIView commitAnimations];