Friday, June 27, 2014

IPhone: message passing between different views using notifications

In the sender view

[[NSNotificationCenter defaultCenter] postNotificationName:@"Mynotification" object:nil];



In the receiver view
(In view did load)

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(functionToRespondMyNotification) name:@"Mynotification" object:nil];



#pragma mark custom notification responders

-(void) functionToRespondMyNotification
{
    // response
}

In viewdiddisappear

 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"Mynotification" object:nil];

Iphone Array of strings and searching particular string - NSMutableArray

Usage
NSMutableArray *myArray = [NSMutableArray array];
[myArray addObject:@"first string"]; // same with float values
[myArray addObject:@"second string"];
[myArray addObject:@"third string"];
int i;
int count;
for (i = 0, count = [myArray count]; i < count; i = i + 1)
{
   NSString *element = [myArray objectAtIndex:i];
   NSLog(@"The element at index %d in the array is: %@", i, element); // just replace the %@ by %d
}



Search
return [theArray indexOfObject:@"ipod"];

Thursday, June 26, 2014

xcode core data (database) access - search -login

- (BOOL) userLogin:(NSString *)username
                  :(NSString *)password
{
   
    
    NSFetchRequest *userFetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"User"];
    userFetchRequest.predicate = [NSPredicate predicateWithFormat:@"username == %@", username];
    NSError *error;
    NSArray *users = [self.context executeFetchRequest:userFetchRequest error:&error];
    NSManagedObject *matches = nil;
    if ([users count] == 0) {
        NSLog(@"Invalid Username");
        return FALSE;
    } else {
        matches = [users objectAtIndex:0];
        NSLog([NSString stringWithFormat:@"%@",users]);
        NSLog([matches valueForKey:@"username"]);
        NSLog([matches valueForKey:@"password"]);
        NSString *mypass =[matches valueForKey:@"password"];
        if ([mypass isEqualToString:password]) {
            NSLog(@"All correct at login");
            return TRUE;
        }
        else
        {
            NSLog(@"Invalid Password");
            return FALSE;
        }
        
        
       // NSLog([NSString stringWithFormat:@"%d matches found", [objects count]];

    }

Wednesday, June 25, 2014

Xcode create and usage of NSMutableDictionary

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
 [dict setObject:@"John" forKey:@"Firstname"];
 [dict setObject:@"Doe" forKey:@"Lastname"];
 [dict setObject:@"info at objectgraph.com" forKey:@"Email"];
 
 NSLog(@"%@", dict);
 
 NSArray *keys = [dict allKeys];
 
 // values in foreach loop
 for (NSString *key in keys) {
  NSLog(@"%@ is %@",key, [dict objectForKey:key]);
 }

Friday, June 20, 2014

Xcode - Iphone, UITextfiled placeholder color settings

UIColor *color = [UIColor lightTextColor];
YOURTEXTFIELD.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"PlaceHolder Text" attributes:@{NSForegroundColorAttributeName: color}];

Thursday, June 19, 2014

Navigation controller and autorotation in iphone

The navigation controller before the view controller, destroying the code for disabling the autorotation  in the view controller class.

Assigning the class to navigation controller and there placed the code for disabling the autorotation worked.

- (BOOL)shouldAutorotate {
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;

}

--------- Full class for navigation controller
#import "UINavigationPortraitController.h"

@interface UINavigationPortraitController ()

@end

@implementation UINavigationPortraitController

- (BOOL)shouldAutorotate {
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


and the header file

#import <UIKit/UIKit.h>

@interface UINavigationPortraitController : UINavigationController

@end

Wednesday, June 11, 2014

XCODE username password settings in NSUserDefault

For Saving Username and Password I will personally suggest to use Keychain as they are more safer than NSUserDefault in terms of security since Keychain stores data in encrypted form while NSUserDefault stores as plain text. If you still want to use NSUserDefault Here's the way
FOR SAVING
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// saving an NSString
[prefs setObject:txtUsername.text forKey:@"userName"];
[prefs setObject:txtPassword.text forKey:@"password"];

 [prefs synchronize];
FOR RETRIEVING
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// getting an NSString
NSString *savedUsername = [prefs stringForKey:@"userName"];
NSString *savedPassword = [prefs stringForKey:@"password"];

Tuesday, June 10, 2014

Iphone : NSString to NSData conversion

NSString* str = @"teststring";
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];

Monday, June 9, 2014

Cookie setting in iPhone

-(void) setCookie:(NSString *)cookieName:(NSString *)cookieValue:(NSString *)cookieDomain
{
    NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys:
                                cookieDomain, NSHTTPCookieDomain,
                                cookieName, NSHTTPCookieName,
                                cookieValue, NSHTTPCookieValue,
                                @"/", NSHTTPCookiePath,
                                nil];
 
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:[NSHTTPCookie cookieWithProperties:properties]];
}



NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://aaaa.com"]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                                       timeoutInterval:10];

    [self setCookie:@"sessionid" :@"5b0bdfa53414487c537cc05205f3c663" :@"www.aaaa.com"];
    [urlRequest setHTTPMethod: @"GET"];
    NSURLResponse * response = nil;
    NSError * error = nil;
    NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
                                          returningResponse:&response
                                                      error:&error];
    
    if (error == nil)
    {
        // Parse data here
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(str);
    }