Wednesday, September 25, 2013

Avoid Keyboard in UITableView Cell

The best solution to avoid keyboard in iOS in table view are to use framework called TPKeyboardAvoid https://github.com/michaeltyson/TPKeyboardAvoiding

But, if you need some manual solution here are few codes

-(void) viewDidAppear:(BOOL)animated {
    [super viewDidAppear:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];

}

-(void) viewDidDisappear:(BOOL)animated  {
    [super viewDidDisappear:YES];
    blogParser.delegate = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

-(CGFloat)getLabelHeightForIndex:(NSInteger)index
{
    CGSize maximumSize = CGSizeMake(230, 10000);
    Blog_Comment *comment = comments[index];
    
    CGSize labelHeighSize = [comment.comment sizeWithFont: [UIFont fontWithName:@"Helvetica" size:12.0f]
                                     constrainedToSize:maximumSize
                                         lineBreakMode:NSLineBreakByCharWrapping];
    return labelHeighSize.height;
    
}

#pragma mark - Notification 

-(void) moveTableViewBottomRowUp:(NSNotification *)note {
    NSDictionary *userInfo = [note userInfo];
    CGSize kbSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    kKeyboardHeight = kbSize.height;
    
    NSTimeInterval duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        UIEdgeInsets edgeInsets = UIEdgeInsetsMake(0, 0, kbSize.height, 0);
        [_tableView setContentInset:edgeInsets];
        [_tableView setScrollIndicatorInsets:edgeInsets];
//        [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[_tableView numberOfRowsInSection:0]-1 inSection:0]
//                          atScrollPosition:UITableViewScrollPositionTop
//                                  animated:YES];
    }];
}

-(void) moveTableViewBottom2Normal:(NSNotification *)note {
    NSDictionary *userInfo = [note userInfo];
    NSTimeInterval duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:duration animations:^{
        UIEdgeInsets edgeInsets = UIEdgeInsetsZero;
        [_tableView setContentInset:edgeInsets];
        [_tableView setScrollIndicatorInsets:edgeInsets];
    }];
}

-(void) assignKeyBoardHeigh:(NSNotification *) note {
    NSDictionary *userInfo = [note userInfo];
//    NSTimeInterval duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGSize kbSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    kKeyboardHeight = kbSize.height;
}

-(void) keyboardWillShow:(NSNotification *)note {
    [self assignKeyBoardHeigh:note];
    [self moveTableViewBottomRowUp:note];
    [self moveTextFieldUp];
}

-(void) keyboardWillHide:(NSNotification *)note {
//    [self moveTableViewBottom2Normal:note];
    [self moveTexyFieldDown];
}


-(void) moveTextFieldUp {
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:0.2];
    CGRect frame = viewComment.frame;
    frame.origin.y = self.view.bounds.size.height - kKeyboardHeight - frame.size.height;
    viewComment.frame = frame;
    // DLog(@"%f", viewComment.frame.origin.y);
    [UIView commitAnimations];
}

-(void) moveTexyFieldDown {
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:0.2];
    CGRect frame = viewComment.frame;
    frame.origin.y = self.view.bounds.size.height - frame.size.height;
    viewComment.frame = frame;
    
    // DLog(@"%f", viewComment.frame.origin.y);
    [UIView commitAnimations];
}



http://iphoneimei.info/

Thursday, September 12, 2013

iOS7 related changes and fixes


iOS 7 New Design Guidelines









Every app needs an app icon and a launch image. In addition, some apps need custom icons to represent app-specific content, functions, or modes in navigation bars, toolbars, and tab bars.
Unlike other custom artwork in your app, the icons and images listed in Table 38-1 must meet specific criteria so that iOS can display them properly. In addition, some icon and image files have naming requirements. (If you need to support standard-resolution iPhone or iPod touch devices, divide by 2 the high-resolution sizes listed below.)

Table 38-1Size (in pixels) of custom icons and images
Description
Size for iPhone 5 and iPod touch (high resolution)
Size for iPhone and iPod touch (high resolution)
Size for iPad (high resolution)
Size for iPad 2 and iPad mini (standard resolution)
App icon (required for all apps)
120 x 120
120 x 120
152 x 152
76 x 76
App icon for the App Store (required for all apps)
1024 x 1024
1024 x 1024
1024 x 1024
1024 x 1024
Launch image (required for all apps)
640 x 1136
640 x 960
1536 x 2048 (portrait)
2048 x 1536 (landscape)
768 x 1024 (portrait)
1024 x 768 (landscape)
Spotlight search results icon (recommended)
80 x 80
80 x 80
80 x 80
40 x 40
Settings icon (recommended)
58 x 58
58 x 58
58 x 58
29 x 29
Toolbar and navigation bar icon (optional)
About 44 x 44
About 44 x 44
About 44 x 44
About 22 x 22
Tab bar icon (optional)
About 50 x 50 (maximum: 96 x 64)
About 50 x 50 (maximum: 96 x 64)
About 50 x 50 (maximum: 96 x 64)
About 25 x 25 (maximum: 48 x 32)
Default Newsstand cover icon for the App Store (required for Newsstand apps)
At least 512 pixels on the longest edge
At least 512 pixels on the longest edge
At least 512 pixels on the longest edge
At least 256 pixels on the longest edge
Web clip icon (recommended for web apps and websites)
120 x 120
120 x 120
152 x 152
76 x 76
For all images and icons, the PNG format is recommended. You should avoid using interlaced PNGs.
The standard bit depth for icons and images is 24 bits—that is, 8 bits each for red, green, and blue—plus an 8-bit alpha channel.
You don’t need to constrain your palette to web-safe colors.




Link :
https://developer.apple.com/library/prerelease/ios/documentation/UserExperience/Conceptual/MobileHIG/IconMatrix.html#//apple_ref/doc/uid/TP40006556-CH27-SW1

Problem :
How to disable back swipe gesture for UINavigationControl UINavigationBar in iOS7

Solution :
Here is the code


if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
        self.edgesForExtendedLayout = UIRectEdgeNone;

self.navigationController.interactivePopGestureRecognizer.enabled = NO;

1:   #pragma mark  
2:  #pragma mark Hide / Show TabBar  
3:  - (void) hideNavBar {  
4:    UINavigationBar *navBar = self.navigationController.navigationBar;  
5:    navBar.hidden = TRUE;  
6:    
 if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {  
     DLog(@"< iOS6");  
     // Load resources for iOS 6.1 or earlier  
   } else {  
     DLog(@"iOS 7");  
     self.navigationController.interactivePopGestureRecognizer.enabled = NO; // Load resources for iOS 7 or later  
   }   
7: } 8: - (void) showNavBar { 9: UINavigationBar *navBar = self.navigationController.navigationBar; 10: navBar.hidden = FALSE; 11: } 12: #pragma mark 13: #pragma mark - View 14: - (void)viewDidLoad { 15: [super viewDidLoad]; 16: [self hideNavBar]; 17: }

http://stackoverflow.com/questions/17209468/how-to-disable-back-swipe-gesture-in-uinavigationcontroller-on-ios-7


Things Every App Must Do

  • Update the app icon.
    In iOS 7, app icons for high-resolution iPhone and iPod touch are 120 x 120 pixels; for high-resolution iPad, app icons are 152 x 152 pixels. (To learn more about all icon sizes, see “Icon and Image Sizes”.)
    Note that iOS 7 doesn’t apply shine or a drop shadow to the app icon. And, although iOS 7 still applies a mask that rounds the corners of an app icon, it uses a different corner radius than earlier versions of iOS.
  • Update the launch image to include the status bar area if it doesn’t already do so.
  • Support Retina display and iPhone 5 in all your artwork and designs, if you’re not already doing so.

Things Every App Should Do

  • Make sure that app content is discernible through translucent UI elements—such as bars and keyboards—and the transparent status bar. In iOS 7, view controllers use full-screen layout (to learn more, see Using View Controllers).
  • Redesign custom bar button icons. In iOS 7, bar button icons are lighter in weight and have a different style. For some design guidance, see “Bar Button Icons”.
  • Prepare for borderless buttons by reassessing the utility of button background images and bezels in your layout.
  • Examine your app for hard-coded UI values—such as sizes and positions—and replace them with those you derive dynamically from system-provided values. Use Auto Layout to help your app respond when layout changes are required. (If you’re new to Auto Layout, learn about it by readingAuto Layout Guide.)
  • Examine your app for places where the metrics and style changes of UIKit controls and views affect the layout and appearance. For example, switches are wider, grouped tables are no longer inset, and progress views are thinner. For more information on specific UI elements, see Bars and Bar Buttons,Content ViewsControls, and Temporary Views.
  • Adopt Dynamic Type. In iOS 7, users can adjust the text size they see in apps. When you adopt Dynamic Type, you get text that responds appropriately to user-specified size changes. For more information, see Using Fonts.
  • Expect users to swipe up from the bottom of the screen to reveal Control Center. If iOS determines that a touch that begins at the bottom of the screen should reveal Control Center, it doesn’t deliver the gesture to the currently running app. If iOS determines that the touch should not reveal Control Center, the touch may be slightly delayed before it reaches the app.
  • Revisit the use of drop shadows, gradients, and bezels. Because the iOS 7 aesthetic is smooth and layered—with much less emphasis on using visual effects to make UI elements look physical—you may want to rethink these effects.
  • If necessary, update your app to best practices for iOS 6—such as Auto Layout and storyboards—and ensure that the app doesn’t use deprecated APIs.
Now that you have a better idea of the types of things you need to do, learn more about changes in view controllers, tinting, and fonts by reading Appearance and Behavior.
SourceSource


Monday, September 9, 2013

How to Fix “Your account is not valid for use in the store” switch iTune account country on iOS

Step 1: Open the App Store



Step 2: Select Featured tab ( 1st tab )





















Step 3: Scroll down to the bottom and select View Apple ID






















Step 4: DONE ! Yep you are done. That is all you need to do. :)






















Now your account will be automatically switched to your country store.


Source

Sunday, September 1, 2013

Objective-C MACRO #define

So of my favorite macro I use in most of my projects are as follows

From NSScreenCast
 #define URLIFY(urlString) [NSURL URLWithString:urlString]  
 #define F(string, args...) [NSString stringWithFormat:string, args]  
 #define ALERT(title, msg) [[[UIAlertView alloc]     initWithTitle:title\  
                             message:msg\  
                             delegate:nil\  
                             cancelButtonTitle:@"OK"\  
                             otherButtonTitles:nil] show]  


Text Alighment to support iOS 5 and iOS 6
 #ifdef __IPHONE_6_0  
   # define ALIGN_CENTER NSTextAlignmentCenter  
 #else  
   # define ALIGN_CENTER UITextAlignmentCenter  
 #endif  
 #ifdef __IPHONE_6_0  
   # define ALIGN_RIGHT NSTextAlignmentRight  
 #else  
   # define ALIGN_RIGHT UITextAlignmentRight  
 #endif  
 #ifdef __IPHONE_6_0  
   # define ALIGN_LEFT NSTextAlignmentLeft  
 #else  
   # define ALIGN_LEFT UITextAlignmentLeft  
 #endif  


My Personal Macro's
 #define GOBACK [self.navigationController popViewControllerAnimated:YES]  
 #define DELEGATE_OK(delegateMethod) [self.delegate respondsToSelector:@selector(delegateMethod)]  


For Screen Size after Orientation Change

 #define SCREEN_WIDTH ((([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait) || ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown)) ? [[UIScreen mainScreen] bounds].size.width : [[UIScreen mainScreen] bounds].size.height)  
 #define SCREEN_HEIGHT ((([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait) || ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown)) ? [[UIScreen mainScreen] bounds].size.height : [[UIScreen mainScreen] bounds].size.width)  

And some funny One from

Funny C/C++ declarations

http://www.gnu.org/fun/jokes/declarations.html




Thursday, August 29, 2013

POST Multipart Form Data using AFNetworking iOS

1:  NSString *urlString = @"yourUrl";  
2:    NSURL* url = [NSURL URLWithString:urlString];  
3:      
4:    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];  
5:    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];  
6:    NSURL *localVideoURL = [NSURL URLWithString:[userDefaults objectForKey:@"videoURL"]];  
7:    NSData *videoData = [NSData dataWithContentsOfURL:localVideoURL];  
8:      
9:    NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:nil parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {  
10:      [formData appendPartWithFileData:videoData name:@"video_file" fileName:@"testvideo.mov" mimeType:@"video/quicktime"];  
11:      [formData appendPartWithFormData:[[BAUserInfoParser userInfoJson] dataUsingEncoding:NSUTF8StringEncoding] name:@"userInfo"];  
12:      [formData appendPartWithFormData:[[userDefaults objectForKey:@"transactionReceiptData"] dataUsingEncoding:NSUTF8StringEncoding] name:@"transactionData"];  
13:    }];  
14:      
15:    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];  
16:    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {  
17:      // NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);  
18:      float uploadPercentge = (float)totalBytesWritten / (float)totalBytesExpectedToWrite;  
19:      float uploadActualPercentage = uploadPercentge *100;  
20:      [lblUploadInfoText setText:[NSString stringWithFormat:@"%.2f %%",uploadActualPercentage]];  
21:      if (uploadActualPercentage >= 100) {  
22:        lblStatus.text = @"Waitting for response ...";  
23:      }  
24:      progressBar.progress = uploadPercentge;  
25:    }];  
26:    [httpClient enqueueHTTPRequestOperation:operation];  
27:      
28:    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {  
29:  lblStatus.text = @"Upload Complete";  
30:   NSData *JSONData = [operation.responseString dataUsingEncoding:NSUTF8StringEncoding];  
31:      NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:nil];  
32:      }  
33:      failure:^(AFHTTPRequestOperation *operation, NSError *error) {  
34:        NSLog(@"error: %@", operation.responseString);  
35:        NSLog(@"%@",error);  
36:    }];  
37:    [operation start];  
38:  }  


Swift 2.0

1:  let imageData = UIImageJPEGRepresentation(self.myImage.image, 0.2)  
2:        let manager = AFHTTPRequestOperationManager(baseURL: nil)  
3:        manager.requestSerializer.setValue(self.accessToken, forHTTPHeaderField: "Authorization")  
4:        manager.requestSerializer.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")  
5:        manager.responseSerializer = AFJSONResponseSerializer()  
6:        let operation = manager.POST(URL.PackageImageUploadURL, parameters: parameters, constructingBodyWithBlock: { formData in  
7:          formData.appendPartWithFileData(  
8:            imageData!,  
9:            name: "image",  
10:            fileName: "image.jpg",  
11:            mimeType: "image/jpeg")  
12:          }, success: { (operation, response) in 
13:                                 print(response)    
15:          }, failure: { (operation, error) in  
16:            // TODO: - Handle error case  
17:            print(error)  
19:        })  
20:        operation?.start()  

Friday, August 16, 2013

Auto Adjusting UIButton On a UIView

Here is a simple requirement
- You can have any number of UIButtons say from 2 to 5, you need to adjust them in the horizontal view with each tags

2 Buttons Example :



5 Buttons Example :


 //  
 // BGGridButtonsView.h  
 //  
 // Created by Bishal Ghimire on 8/16/13.  
 // Copyright (c) 2013 Bishal Ghimire. All rights reserved.  
 //  
 #import <UIKit/UIKit.h>  
 @class BGGridButtonsView;  
 @protocol BGGridButtonsViewDelegate <NSObject>  
 -(void) selectedButton:(int)buttonNo forTagNo:(int)tagNo;  
 @end  
 @interface BGGridButtonsView : UIView  
 @property (nonatomic, strong) NSArray *buttonNames;  
 @property(assign) id <BGGridButtonsViewDelegate> delegate;  
 @end  


 //  
 // BGGridButtonsView.m  
 // Created by Bishal Ghimire on 8/16/13.  
 // Copyright (c) 2013 Bishal Ghimire. All rights reserved.  
 //  
 #import "BGGridButtonsView.h"  
 @implementation BGGridButtonsView  
 @synthesize buttonNames;  
 -(void) baseInit {  
   int count = [buttonNames count];  
   CGFloat padding = 10;  
   CGFloat width = self.frame.size.width / count - padding;  
   for (int i = 0; i < count; i++) {  
     CGFloat ptX = i * (width + padding) ;  
     UIButton *button = [self addMyButton:i+1];  
     button.frame = CGRectMake(ptX, 0, width, 20);  
     [self addSubview:button];  
   }  
 }  
 -(void) buttonAction:(UIButton *) sender {  
   DLog(@"%d", sender.tag);  
 }  
 - (UIButton *) addMyButton:(int)tagNo  
 {  
   UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];  
   [button setTitle:buttonNames[tagNo-1] forState:UIControlStateNormal];  
   button.backgroundColor = [UIColor clearColor];  
   [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];  
   //UIImage *buttonImageNormal = [UIImage imageNamed:@""];  
   UIImage *buttonImageNormal = [UIImage imageNamed:@""];  
   UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:2 topCapHeight:2];  
   [button setBackgroundImage:strechableButtonImageNormal forState:UIControlStateNormal];  
   //  UIImage *buttonImagePressed = [UIImage imageNamed:@""];  
   //  UIImage *strechableButtonImagePressed = [buttonImagePressed stretchableImageWithLeftCapWidth:2 topCapHeight:2];  
   //  [button setBackgroundImage:strechableButtonImagePressed forState:UIControlStateHighlighted];  
   [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];  
   button.tag = tagNo;  
   [self addSubview:button];  
   return button;  
 }  
 - (id)initWithFrame:(CGRect)frame  
 {  
   self = [super initWithFrame:frame];  
   if (self) {  
   }  
   return self;  
 }  
 - (void)drawRect:(CGRect)rect  
 {  
   [self baseInit];  
 }  
 @end  

Finally On your View Controller
 #import "BGGridButtonsView.h"  
 @interface TestVC : UIViewController  
  <BGGridButtonsViewDelegate>  

 -(void) viewDidAppear:(BOOL)animated   {  
   BGGridButtonsView *buttonsGrid = [[BGGridButtonsView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];  
   buttonsGrid.buttonNames = @[ @"Call", @"PMS"];  
   buttonsGrid.tag = 1;  
   buttonsGrid.backgroundColor = [UIColor redColor];  
   [self.view addSubview:buttonsGrid];  
 }  

 #pragma mark Delegate Method  
 -(void) selectedButton:(int)buttonNo forTagNo:(int)tagNo {  
   DLog(@"%d , %d",buttonNo, tagNo);  
 }  

Tuesday, August 13, 2013

Git setup on Mac, Linux or Unix using Terminal


Git global setup:

git config --global user.name "Bishal Ghimire"
git config --global user.email  "you@ youremail.com"

Create Repository

mkdir yourProject
cd yourProject
git init
touch README
git add README
git commit -m 'first commit'
git remote add origin git@git.youremail.com: yourProject.git
git push -u origin master


Existing Git Repo?
cd existing_git_repo
git remote add origin git@git. youremail.com:yourProject.git
git push -u origin master


That is it ... 

Bonus Codes

Force Push Local to server

git push origin master --force


Force Pull From Server to local



# fetch from the default remote, origin
git fetch
# reset your current branch (master) to origin's master
git reset --hard origin/master



Branch and Merge




# fetch from the default remote, origin
git fetch
# create a branch at your current master
git branch old-master
# reset to origin's master
git reset --hard origin/master
# merge your old master, keeping "our" (origin/master's) content
git merge -s ours old-master

Common Git Issues And Solutions 


Issue 1 : "File Locked, unable to edit in XCode"

Solution : Change File Read Write permission 

As you have made force changes from the file from internet you are more likely to lock the files, which XCode will not allow you to edit all you can do is read the files only !
To chage that on your root folder of your terminal

sudo chmod -R 0777 ./*


Issue 2 : “fatal: remote origin already exists”


Solution :
Other 'origin' alreadt exists on remote server or is already on use

git remote rm origin
git remote add origin git@youremail.github.com:youriOSapp/my_app.git
git push -u origin --all # pushes up the repo and its refs for the first time


resync-git-repo-with-new-gitignore-file


git rm -r --cached .
git add .git commit -m ".gitignore is now working"

git-mergetool

git-mergetool - Run merge conflict resolution tools to resolve merge conflicts
Syntax - 


git mergetool [--tool=<tool>] [-y | --[no-]prompt] [<file>...]
Eg -
git mergtool --tool=emerge

Keyboard Tips 
n =  next
a / b = alter version

Read More At :

http://www.mac-terminal.com/files-and-folders/permissions/chmod/
http://stackoverflow.com/a/4787356/1294448
http://stackoverflow.com/questions/10904339/github-fatal-remote-origin-already-exists