Friday 28 February 2014

JSON obj c

Get values of particular key in nsdictionary:

 I refered this link for this blog.(http://stackoverflow.com/questions/16233425/get-values-of-particular-key-in-nsdictionary)

HERE IS THE PASTIE URL FOR JSON DATA :
http://pastie.org/8811638


Now Check the Scenario for the getting objects.

Following will give you the desired object :

NSDictionary *dict=[results valueForKeyPath:@"data.abcd"][0];

For individual:

NSString *categoryString=[[results valueForKeyPath:@"data.abcd"][0] objectForKey:@"Category"];
NSString *idString=[[results valueForKeyPath:@"data.abcd"][0] objectForKey:@"id"];
NSString *titleString=[[results valueForKeyPath:@"data.abcd"][0] objectForKey:@"title"];

Also,

NSString *categoryString=dict[@"Category"];
NSString *idString=dict[@"id"];
NSString *titleString=dict[@"title"];

Tuesday 25 February 2014

How to debug EXC_BAD_ACCESS

I have found one cool blog for EXC_BAD_ACCESS  and write same scenario for understanding this issue. :

You have to accept the fact that sooner or later you will need to debug a EXC_BAD_ACCESS problem and most probably won’t be easy to.

This article however is about how to make the process easier, in some cases easy as a piece of cake.

What does EXC_BAD_ACCESS mean?

EXC_BAD_ACCESS means that message was sent to a point in the memory where there’s no instance of a class to execute it. Thus “bad access”

When EXC_BAD_ACCESS happen?

You will get EXC_BAD_ACCESS in 3 cases:
  1. An object is not initialized
  2. An object is already released
  3. Something else that is not very likely to happen
That’s already a good starting point. Start using the debugger, if you recently added a new object to the class you’re working on, put a breakpoint at the line before the freshly added object is used for the first time and check the values in the debugger.

What’s happening most though is that you will be sending a message to an overreleased object – i.e. object that is gone from the call stack. In this cases everything (and indeed everything) you will get in the console will be just : 

                EXC_BAD_ACCESS.

This is because the object is gone, there is no information what class was it, or what source file or anything else. That’s really tough to debug with NSLog … NSLog is helpful, but you need to put 1,000 NSLogs around to fetch where is the problem.

Enabling NSZombies

The solution to overreleased objects are the zombies. When this feature is enabled, a dummy object (a zombie) is kept on the place of every released object, thus allowing to debug objects which were released already. Very easy to enable:
  1. Double click your executable in the “Executables” in XCode
  2. Open “Arguments” tab
  3. In “Variables to be set in the environment” (that’s the list at the bottom, be careful which one you edit) click the “+” button and for name of the variable enter “NSZombieEnabled” and for value “YES”
Voila!
Now instead of wondering what’s going on and which exact object produced the problem, you’ll see exactly which class is the trouble maker, and you’ll debug it quite fast.
Beware the zombies though
Just a reminder not to leave the zombies enabled, when you submit your app to the App store. Also, it’s a good practice to disable them if you don’t really need them.

Using this blog : http://www.touch-code-magazine.com/how-to-debug-exc_bad_access/

Saturday 15 February 2014

[Objective-C] Use database with sql (lite)

Here a simple tutorial to use SQLite in Objective-C to make complex iphone|ipad applications that uses a database!


Now, create a new project and import SQLite library. Generally it is located here:
/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.X.X.X.sdk/usr/lib/libsqlite3.dylib

In your header file, you need t add the import and create sqlite3 class in your interface:


 I show only three method that uses the db, SELECT, DELETE, INSERT.

READ DATA (like SELECT * FROM XXX) : ----->>

- (NSMutableArray*) readDataFromDatabase  {
   dataArray  = [[NSMutableArray alloc] init];
   dataStored = [[NSMutableDictionary alloc] init];
 
   NSString *name;
   NSString *address;

   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
   NSString *documentsDirectory = [paths objectAtIndex:0];
   NSString *path = [documentsDirectory stringByAppendingPathComponent:@"MyDB.sqlite"];

   if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
        const char *sql = "SELECT * FROM tabella";
        sqlite3_stmt *statement;
        if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
             while (sqlite3_step(statement) == SQLITE_ROW) {
                      name =   [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
                      address = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
   
                       [dataStored setObject:name forKey:@"name"];
                       [dataStored setObject:address forKey:@"address"];
   
                        [dataArray addObject:[dataStored copy]];
              }
         }
         sqlite3_finalize(statement);
    }
   sqlite3_close(database);
   [dataStored release];

   return dataArray;
}
In this method, that return a NSMutableArray, I used a NSMutableDictionary (dataStored) and a NSMutableArray (dataArray).
Now we have a dataArray with lists of the select query!
DELETE DATA FROM xxx :
- (void) deleteDataFromDatabase:(id) data
{  
   NSMutableDictionary *d = data;

   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
   NSString *documentsDirectory = [paths objectAtIndex:0];
   NSString *path = [documentsDirectory stringByAppendingPathComponent:@"MyDB.sqlite"];

   sqlite3_stmt *delete_statment = nil;
   if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
         if (delete_statment == nil) {
              const char *sql = "DELETE FROM tabella WHERE name=? AND address=?";
              if (sqlite3_prepare_v2(database, sql, -1, &delete_statment, NULL) != SQLITE_OK) {
                  NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
              }
         }
         sqlite3_bind_text(delete_statment, 2, [[d objectForKey:@"name"] UTF8String], -1,  SQLITE_TRANSIENT);
         sqlite3_bind_text(delete_statment, 3, [[d objectForKey:@"address"] UTF8String], -1,  SQLITE_TRANSIENT);

         int success = sqlite3_step(delete_statment);
 
         if (success != SQLITE_DONE) {
              NSAssert1(0, @"Error: failed to save priority with message '%s'.", sqlite3_errmsg(database));
         } else {
              sqlite3_reset(delete_statment);
         }
    }
    sqlite3_close(database);
}
Here, you can delete a value from db. (delete from tabella where x=0 and y=0).
It accept ad method parameter an object, that is necessary a NSMutableDictionary (first row).
INSERT DATA :

- (void) insertDataInDatabase:(NSString*)name address:(NSString*)address
{
   sqlite3_stmt *insert_statement = nil;
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
   NSString *documentsDirectory = [paths objectAtIndex:0];
   NSString *path = [documentsDirectory stringByAppendingPathComponent:@"MyDB.sqlite"];

   if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
        if (insert_statement == nil) {
           static char *sql = "INSERT INTO tabella (name,address) VALUES(?,?)";
           if (sqlite3_prepare_v2(database, sql, -1, &insert_statement, NULL) != SQLITE_OK) {
                NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
           }

           sqlite3_bind_text(insert_statement, 2, [name UTF8String], -1,  SQLITE_TRANSIENT );
           sqlite3_bind_text(insert_statement, 3, [address UTF8String], -1, SQLITE_TRANSIENT );
        }
        int success = sqlite3_step(insert_statement);
 
        sqlite3_reset(insert_statement);
        if (success != SQLITE_ERROR) {
            NSLog(@"error");
        }
   }
   sqlite3_finalize(insert_statement);
   sqlite3_close(database);
}
In this method you can add values to the table.
First of all operations, you need call createEditableCopyOfDatabaseIfNeeded that locate (and copy to exec path) the db:
 
- (void) createEditableCopyOfDatabaseIfNeeded  {
     BOOL success;
     NSFileManager *fileManager = [NSFileManager defaultManager];
     NSError *error;
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
     NSString *documentsDirectory = [paths objectAtIndex:0];
     NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"MyDB.sqlite"];
     success = [fileManager fileExistsAtPath:writableDBPath];
     if (success) return;
     NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"MyDB.sqlite"];
     success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
     if (!success) {
          NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
     }
}
It copy current .sqlite file in your device.

Simple Tricks of Obj C :

Simple Tricks of Obj C :

1. Get All HTTP Headers:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:
                                                 (NSURLResponse *)response{
     NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
     NSDictionary *dic = [httpResponse allHeaderFields];
}
 

2. Convert NSMutableData to NSString:

 NSString *strData = [[NSString alloc]initWithData:returnData 
                         encoding:NSUTF8StringEncoding];
 NSLog(@"strData : %@",strData);

--->  If you do this: NSLog(@"%@", returnData);
The NSData will be logged in hex format. I think that is probably what you are after.
If you want to turn it into a string and log the string, you first need to find out what character set was used. The default character set for HTTP is not UTF-8, it is ISO-8859-1. One way to do that is to examine the Content-Type header for the charset section.


NSString *s = @"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
NSLog(@"%@", s); // => foobarbazfoo


4. In Objective-C, how do I test the object type?

or the line below, we have some poorly formed data that can be an NSArray, an NSDictionary or (null).

NSArray *hits = [[[myXML objectForKey: @"Answer"] objectForKey: @"hits"] 
                 objectForKey: @"Hit"];

These are the tests that were performed:

NSLog(@"%@",[hits class]);

if ([hits isMemberOfClass:[NSMutableArray class]]){
    NSLog(@"%@",[hits class]);
}

if ([hits  isMemberOfClass:[NSMutableDictionary class]]){
    NSLog(@"%@",[hits class]);
}

if ([hits isMemberOfClass:[NSArray class]]){
    NSLog(@"%@",[hits class]);
}

if ([hits isMemberOfClass:[NSDictionary class]]){
    NSLog(@"%@",[hits class]);
}

if ([hits  isKindOfClass:[NSMutableDictionary class]]){
    NSLog(@"%@",[hits class]);
}

if ([hits  isKindOfClass:[NSDictionary class]]){
    NSLog(@"%@",[hits class]);
}

if ([hits  isKindOfClass:[NSArray class]]){
    NSLog(@"%@",[hits class]);
}

if ([hits isKindOfClass:[NSMutableArray class]]){
    NSLog(@"%@",[hits class]);
}

5. NSString

The basic NSString class is immutable, which means its contents are set at creation and cannot later be changed. If you need to represent a different string, you must create a new string object, like this:

    NSString *name = @"John";
    name = [name stringByAppendingString:@"ny"];    // returns a new string object
 
The NSMutableString class is the mutable subclass of NSString, and allows you to 
change its character contents at runtime using methods like 
appendString: or appendFormat:, like this: 

    NSMutableString *name = [NSMutableString stringWithString:@"John"];
    [name appendString:@"ny"];   // same object, but now represents "Johnny"

 
First of all, it is very important to note, that there is a big difference between UITextView and UILabel when it comes to how text is rendered. Not only does UITextView have insets on all borders, but also the text layout inside it is slightly different.

Therefore, sizeWithFont: is a bad way to go for UITextViews.

Instead UITextView itself has a function called sizeThatFits: which will return the smallest size needed to display all contents of the UITextView inside a bounding box, that you can specify.
The following will work equally for both iOS 7 and older versions and as of right now does not include any methods, that are deprecated.

Simple Solution

- (CGFloat)textViewHeightForAttributedText: (NSAttributedString*)text 
         andWidth: (CGFloat)width {
    UITextView *calculationView = [[UITextView alloc] init];
    [calculationView setAttributedText:text];
    CGSize size = [calculationView sizeThatFits:CGSizeMake(width, FLT_MAX)];
    return size.height;
}
This function will take a NSAttributedString and the desired width as a CGFloat and
return the height needed

Check this :
http://stackoverflow.com/questions/18368567/uitableviewcell-with-uitextview-height-in-ios-7
http://stackoverflow.com/questions/19028743/ios7-uitextview-contentsize-height-alternative


7. objective - C : Loading image from URL?


- (void)loadImage:(NSURL *)imageURL{
    NSOperationQueue *queue = [NSOperationQueue new];
    NSInvocationOperation *operation = [[NSInvocationOperation alloc]
                                        initWithTarget:self
                                        selector:@selector(requestRemoteImage:)
                                        object:imageURL];
    [queue addOperation:operation];
}

- (void)requestRemoteImage:(NSURL *)imageURL {
    NSData *imageData = [[NSData alloc] initWithContentsOfURL:imageURL];
    UIImage *image = [[UIImage alloc] initWithData:imageData];
    
    [self performSelectorOnMainThread:@selector(placeImageInUI:) 
          withObject:image waitUntilDone:YES];
}

- (void)placeImageInUI:(UIImage *)image{
    [latestIssueBtn setImage:image forState:UIControlStateNormal];
}

8.CocoaPods :

1. What is CocoaPods?
(http://guides.cocoapods.org/using/getting-started.html#installation)

CocoaPods manages library dependencies for your Xcode projects.

The dependencies for your projects are specified in a single 
text file called a Podfile. CocoaPods will resolve dependencies between libraries, 
fetch the resulting source code, then link it together in an Xcode workspace to 
build your project.

Ultimately the goal is to improve discoverability of, 
and engagement in, third party open-source libraries by creating a more centralized 
ecosystem.

2. What is Gem ??
(http://rubydoc.info/gems/objc/0.0.3/frames)
This gem is a test suite runner for Objective-C files 
to allow for the easy execution of a test suite without the hassle 
of managing an Xcode Project File

Terminal Steps to install Pod. :

  • sudo gem update --system
  • pod install
  • touch Podfile
  • open -e Podfile
  • pod update

Refer Links :



  • Open the XIB file causing problems
  • Click on file's owner icon on the left bar (top one, looks like a yellow outlined box)
  • If you don't see the right-hand sidebar, click on the third icon above "view" in your toolbar.
    This will show the right-hand sidebar
  • In the right-hand sidebar, click on the third tab--the one that looks a bit like a newspaper
  • Under "Custom Class" at the top, make sure Class is the name of the ViewController that should
    correspond to this view. If not, enter it
  • In the right-hand sidebar, click on the last tab--the one that looks like a circle with an arrow in it
  • You should see "outlets" with "view" under it. Drag the circle next to it over to the "view" icon
    on the left bar (bottom one, looks like a white square with a thick gray outline
  • Save the xib and re-run


I can generally fix it by remaking the connection between File's Owner and the view.
Control-drag from the File's owner to your View (in IB) and select view from the pop-up menu.

10. Force a WebView link to launch Safari?


-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request 
                navigationType:(UIWebViewNavigationType)navigationType; 
{
    NSURL *requestURL =[request URL]; 
    if (([[requestURL scheme ] isEqualToString: @"http"] || 
         [[requestURL scheme] isEqualToString: @"https"] || 
         [[requestURL scheme] isEqualToString: @"mailto"]) 
        && (navigationType == UIWebViewNavigationTypeLinkClicked)){ 

        return ![[UIApplication sharedApplication ] openURL:requestURL]; 
    }
    return YES; 
}

Autolayout is great. But at times you need to use a mixture of Storyboard and programmatically generated UI code. In this case Autolayout can overwrite your code settings. The trick is to use the following method:

- (void)viewDidLayoutSubviews
{

}
viewDidLayoutSubviews gets called after it processes autolayout constraints so if you need your UI code to take precedent, then you can specify things here and your code will win over autolayout.


12. Random Loream Ipsum :

- (NSString *)randomLorumIpsum {   
     NSString *lorumIpsum = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent non quam ac massa viverra semper. Maecenas mattis justo ac augue volutpat congue. Maecenas laoreet, nulla eu faucibus gravida, felis orci dictum risus, sed sodales sem eros eget risus. Morbi imperdiet sed diam et sodales. Vestibulum ut est id mauris ultrices gravida. Nulla malesuada metus ut erat malesuada, vitae ornare neque semper. Aenean a commodo justo, vel placerat odio. Curabitur vitae consequat tortor. Aenean eu magna ante. Integer tristique elit ac augue laoreet, eget pulvinar lacus dictum. Cras eleifend lacus eget pharetra elementum. Etiam fermentum eu felis eu tristique. Integer eu purus vitae turpis blandit consectetur. Nulla facilisi. Praesent bibendum massa eu metus pulvinar, quis tristique nunc commodo. Ut varius aliquam elit, a tincidunt elit aliquam non. Nunc ac leo purus. Proin condimentum placerat ligula, at tristique neque scelerisque ut. Suspendisse ut congue enim. Integer id sem nisl. Nam dignissim, lectus et dictum sollicitudin, libero augue ullamcorper justo, nec consectetur dolor arcu sed justo. Proin rutrum pharetra lectus, vel gravida ante venenatis sed. Mauris lacinia urna vehicula felis aliquet venenatis. Suspendisse non pretium sapien. Proin id dolor ultricies, dictum augue non, euismod ante. Vivamus et luctus augue, a luctus mi. Maecenas sit amet felis in magna vestibulum viverra vel ut est. Suspendisse potenti. Morbi nec odio pretium lacus laoreet volutpat sit amet at ipsum. Etiam pretium purus vitae tortor auctor, quis cursus metus vehicula. Integer ultricies facilisis arcu, non congue orci pharetra quis. Vivamus pulvinar ligula neque, et vehicula ipsum euismod quis. Aliquam ut mi elementum, malesuada velit ac, placerat leo. Donec vel neque condimentum, congue justo a, posuere tortor. Etiam mollis id ligula nec dapibus. Etiam tincidunt, nisi non cursus adipiscing, enim neque tincidunt leo, vel tincidunt quam leo non ligula. Proin a felis tellus. Pellentesque quis purus est. Nam consectetur erat quam, non ultricies tortor venenatis ac. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque at laoreet arcu. Mauris odio lorem, luctus facilisis ligula eget, malesuada pellentesque nulla.";
   
    // Split lorum ipsum words into an array
    //
    NSArray *lorumIpsumArray = [lorumIpsum componentsSeparatedByString:@" "];
   
    // Randomly choose words for variable length
    //
    int r = arc4random() % [lorumIpsumArray count];
    NSArray *lorumIpsumRandom = [lorumIpsumArray objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, r)]];

    // Array to string. Adding '!!!' to end of string to ensure all text is visible.
    //
    return [NSString stringWithFormat:@"%@!!!", [lorumIpsumRandom componentsJoinedByString:@" "]];

}

13.Unselect the selected row if any:

- (void)viewWillAppear:(BOOL)animated  {
    self.tableView.rowHeight = 76.0;

    // Unselect the selected row if any
    // http://forums.macrumors.com/showthread.php?t=577677
    NSIndexPath* selection = [self.tableView indexPathForSelectedRow];
    if (selection)
    {
        [self.tableView deselectRowAtIndexPath:selection animated:YES];
    }
}


14. CGRectMake and NSStringFromCGRect  :


How to NSLog the CGRect and CGFrame

CGRect rect1 = CGRectMake(100, 100, 100, 100);
CGRect rect2 = CGRectMake(190, 190, 100, 100);
 
NSLog(@"rect1: %@", NSStringFromCGRect(rect1));
NSLog(@"rect2: %@", NSStringFromCGRect(rect2));
 
CGSize size1 = CGSizeMake(100, 100);
CGSize size2 = CGSizeMake(190, 190);
 
NSLog(@"size1: %@", NSStringFromCGSize(size1));
NSLog(@"size2: %@", NSStringFromCGSize(size2))
 
 
 
 

15. Trim Audio:

-(BOOL)trimAudio {
    
    // Path of your source LOCAL audio file
    //NSString *strInputFilePath = [[[NSBundle mainBundle] resourcePath] 
                                   stringByAppendingPathComponent:@"MyAudioMemo.m4a"];
    //NSURL *audioFileInput = [NSURL fileURLWithPath:strInputFilePath]; 
 
 
 
    
    // Path of your source DocumentDirectory audio file    
    NSArray *pathComponents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                               NSUserDomainMask, YES);
    NSString *documentsDirectoryPath = [pathComponents objectAtIndex:0];
    NSString *strInputFilePath = [NSString stringWithFormat:@"%@%@",
                                           documentsDirectoryPath,@"/MyAudioMemo.m4a"];
                               
    NSURL *audioFileInput = [NSURL fileURLWithPath:strInputFilePath];

    
    // Path of your destination save audio file
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, 
                                                                NSUserDomainMask, YES);
    NSString *libraryCachesDirectory = [paths objectAtIndex:0];
    libraryCachesDirectory = [libraryCachesDirectory 
                                        stringByAppendingPathComponent:@"Caches"];
    
    NSString *strOutputFilePath = [NSString stringWithFormat:@"%@%@",
                                            libraryCachesDirectory,@"/abc.mp4"];

    NSURL *audioFileOutput = [NSURL fileURLWithPath:strOutputFilePath];
    
    if (!audioFileInput || !audioFileOutput)
    {
        return NO;
    }
    
    [[NSFileManager defaultManager] removeItemAtURL:audioFileOutput error:NULL];
    AVAsset *asset = [AVAsset assetWithURL:audioFileInput];
    
    AVAssetExportSession *exportSession = [AVAssetExportSession 
                                             exportSessionWithAsset:asset
                                             presetName:AVAssetExportPresetAppleM4A];
    
    if (exportSession == nil)
    {
        return NO;
    }
    
    NSLog(@"startTrimTime %f", startTrimTime);
    NSLog(@"endTrimTime %f", endTrimTime);
    
    float startTrimTime = 0;
    float endTrimTime = 5;
    
    CMTime startTime = CMTimeMake((int)(floor(startTrimTime * 100)), 100);
    CMTime stopTime = CMTimeMake((int)(ceil(endTrimTime * 100)), 100);
    CMTimeRange exportTimeRange = CMTimeRangeFromTimeToTime(startTime, stopTime);
    
    exportSession.outputURL = audioFileOutput;
    exportSession.outputFileType = AVFileTypeAppleM4A;
    exportSession.timeRange = exportTimeRange;
    
    [exportSession exportAsynchronouslyWithCompletionHandler:^
     {
         if (AVAssetExportSessionStatusCompleted == exportSession.status)
         {
             NSLog(@"Success!");
             AVAudioPlayer *player = [[AVAudioPlayer alloc] 
                      initWithContentsOfURL:audioFileOutput error:nil];
             [player setDelegate:self];
             [player play];
         }
         else if (AVAssetExportSessionStatusFailed == exportSession.status)
         {
             NSLog(@"failed");
         }
     }];
    
    return YES;
} 
 
 


16.SystemConfiguration.framework appears red

 You could have deleted it from your project by accident I have done this in the past when you delete you must have move to trash instead of remove reference, I had to download xcode again to get it back.

17. Get the position of a CGPoint( which is inside a subview), W.R.T the parentView - ObjectiveC : 

UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];
[self.view addSubview:subView];

CGPoint pointInSubview = CGPointMake(20, 20);
CGPoint pointInSuperview = [self.view convertPoint:pointInSubview fromView:subView];
NSLog(@"%@", NSStringFromCGPoint(pointInSuperview));
 
Prints out {70, 70} to the console


 

 

 

 

 




Friday 7 February 2014

How to lift up the UIView when UITextField is editing ?

I have already return about how to lift up the view when UITextView is editing. Here is the solution of UITextField.

First i am going to declared some global varible for this Scope.

#pragma constant UITextField
  1. static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
  2. static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
  3. static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.6;
  4. static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216;
  5. static const CGFloat LANDSCAPE_KEYBOARD_HEIGHT = 162;

Now we are adding some Textfield Delegate Method :

#pragma mark UITextField delegate method
 
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return NO;
}
 
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    CGRect textFieldRect = [self.view.window convertRect:textField.bounds fromView:textField];
    CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view];
     
    CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
    CGFloat numerator = midline - viewRect.origin.y - MINIMUM_SCROLL_FRACTION * viewRect.size.height;
    CGFloat denominator = (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION) * viewRect.size.height;
    CGFloat heightFraction = numerator / denominator;
     
    if (heightFraction < 0.0) {
        heightFraction = 0.0;
    }
    else if (heightFraction > 1.0) {
        heightFraction = 1.0;
    }
 
    animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= animatedDistance;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    [self.view setFrame:viewFrame];
    [UIView commitAnimations];
}
 
- (void)textFieldDidEndEditing:(UITextField *)textField{
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y += animatedDistance;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    [self.view setFrame:viewFrame];
    [UIView commitAnimations];
}
 

Wednesday 5 February 2014

Objective-C and sqlite’s DATETIME type

Well, I am sharing here just the core things regarding date formatting for saving and retrieving the data from Sqlite to Objective C or vice versa. If you have any problem with this code snippet then I will share the full code that I used for my app.


When you save your data, bind your date value in the sql statement like this way:
  1. NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
  2. [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  3. NSString *dateString=[dateFormat stringFromDate:[NSDate date]];
  4. sqlite3_bind_text(saveStmt, 1, [dateString UTF8String] , -1, SQLITE_TRANSIENT);

and when you retrieve data you have to write this code:

  1. NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
  2. [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  3. NSDate *myDate =[dateFormat dateFromString:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)]];

now you have a variable myDate of NSDate type which you can render in your way:

  1. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  2. [formatter setDateFormat:@"dd-MM-yyyy hh:mm:ss a"];NSLog(@"My Date was : %@", [formatter stringFromDate:myDate]);

You must have to remember 3 things:
  1. in your SQLite date field type should be DATETIME
  2. Date format should be same when you store and when you retrieve
  3. Now you can show in your won way but following the format. Bellow the format details has given.

 
Format: 

     'dd' = Day 01-31
     'MM' = Month 01-12
     'yyyy' = Year 2000
     'HH' = Hour in 24 hour
     'hh' = Hour in 12 hour
     'mm' = Minute 00-59
     'ss' = Second 00-59
     'a' = AM / PM



How to get md5 and SHA1 in objective c (iOS sdk) :

Calculating the md5 and sha1 hash in iOS sdk is pretty simple -


Step 1 – The very first thing you need to do is import CommonCrypto’s CommonDigest.h :
1
. #import <CommonCrypto/CommonDigest.h>

Step 2 – Here is the real code for calculating SHA1 and MD5 hash -

SHA1 -

-(NSString*) sha1:(NSString*)input {
      const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
      NSData *data = [NSData dataWithBytes:cstr length:input.length];
 
      uint8_t digest[CC_SHA1_DIGEST_LENGTH];
 
      CC_SHA1(data.bytes, data.length, digest);
 
      NSMutableString* output = [NSMutableString  stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
 
      for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++){
           [output appendFormat:@"%02x", digest[i]];
      }
      return output;
}

MD5 -
- (NSString *) md5:(NSString *) input {
      const char *cStr = [input UTF8String];
      unsigned char digest[16];
      CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
 
      NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
 
      for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++){
           [output appendFormat:@"%02x", digest[i]];
      }
 
      return  output;
 
}
Hope it will helps..!!!!!!!