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



Friday, August 9, 2013

Create Grid Layout View Matrix Programatically

OutPut




View Controller

 #import "BGGridImagesView.h"  
 -(void) groupLayout {  
   BGGridImagesView *gridView = [[BGGridImagesView alloc] initWithFrame:CGRectMake(0, 0, 140, 100)];  
   [self.view addSubview:gridView];  
 }  


View
BGGridImagesView.h
 #import <UIKit/UIKit.h>  
 @interface BGGridImagesView : UIView  
 @end  


BGGridImagesView.m
 //  
 // BGGridImagesView.m  
 //  
 // Created by Bishal Ghimire on 8/9/13.  
 // Copyright (c) 2013. All rights reserved.  
 //  
 #import "BGGridImagesView.h"  
 @implementation BGGridImagesView  
 - (id)initWithFrame:(CGRect)frame  
 {  
   self = [super initWithFrame:frame];  
   if (self) {  
     [self layoutGrid];  
   }  
   return self;   
 }   
 -(void) layoutGrid {  
   NSInteger grid[10][10];  
   NSInteger k = 0;  
   for (int row = 0; row < 4; row++) {  
     for (int column = 0; column < 5; column++) {  
       k++;  
       grid[row][column] = k;  
       UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(column*30, row * 30, 20, 20)];  
       NSString *string = [[NSString alloc] init];  
       string = [NSString stringWithFormat:@"%d",k];  
       lbl.text = string;  
       [self addSubview:lbl];  
     }  
   }  
 }  
 /*  
 // Only override drawRect: if you perform custom drawing.  
 // An empty implementation adversely affects performance during animation.  
 - (void)drawRect:(CGRect)rect  
 {  
   // Drawing code  
 }  
 */  
 @end  



Using UIButtons
 #pragma mark - Grid Layout  
 #define FACTOR 1.0  
 #define kHeight 85.0f  
 #define kWidth 85.0f  
 #define xPadding 15.0f  
 #define yPadding 25.0f  
 #define kNoOfColumn 3  
 -(void) loadGridImages {  
   UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];  
   int numberOfImages = 30;  
   CGRect frame = self.frame;  
   NSInteger grid[30][30];  
   NSInteger k = 0;  
   BOOL dobreak = NO;  
   CGFloat heightFactor = ( kHeight / kNoOfColumn ) * 3;  
   CGFloat widthFactor = ( kWidth / kNoOfColumn ) * 3;  
   for (int row = 0; row < (numberOfImages / kNoOfColumn) && !dobreak; row++) {  
     for (int column = 0; column < kNoOfColumn; column++) {  
       k++;  
       grid[row][column] = k;  
       DLog(@"%d",k);  
       if (k > numberOfImages) {  
         dobreak = YES;  
         break;  
       }  
       frame.size.height = heightFactor;  
       frame.size.width = widthFactor;  
       frame.origin.x = 10 + ( heightFactor * column) + (10 * column);  
       frame.origin.y = 20 + ( widthFactor * row) + (10 * row);  
       UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];  
       NSString *string = [NSString stringWithFormat:@"%d",k];  
       [button setTitle:string forState:UIControlStateNormal];  
       button.titleLabel.font = [UIFont systemFontOfSize:30];  
       //button.backgroundColor = [UIColor blueColor];  
       [button addTarget:self action:@selector(showActionSheet:) forControlEvents:UIControlEventTouchUpInside];  
       button.frame = frame;  
       button.tag = k;  
       [scrollView addSubview:button];  
     }  
   }  
   [scrollView setContentSize:CGSizeMake(self.frame.size.width - xPadding, (((numberOfImages+1)/2) * heightFactor) * 0.8)];  
   [self addSubview:scrollView];  
 }  

Alternate Code* 
 #define FACTOR 1.0  
 #define kHeight 85.0f  
 #define kWidth 85.0f  
 #define xPadding 15.0f  
 #define yPadding 25.0f  
   
 // Three Grid Layout  
   
 -(void) loadGridImages{  
   int numberOfImages = 9;  
     
   CGRect frame = self.scrollView.frame;  
   for (int i = 0; i < numberOfImages; i++) {  
     int j = 0;  
     if (i < 3) {  
       j = i+3;  
     } else {  
       j = i;  
     }  
       
     if (j%3 == 0 ) {  
       frame.origin.x = xPadding;  
     }  
     else if ((j-1)%3 == 0 ) {  
       frame.origin.x = xPadding * 2 + kWidth * 1 ;  
     } else if ((j+1) %3 == 0) {  
       frame.origin.x = xPadding * 3 + kWidth * 2;  
     }  
       
     // frame.origin.y = ((i/3) * kHeight) + yPadding * 3;  
     frame.origin.y = ((i/3) * kHeight) + yPadding * (i/3);  
   
     frame.size.height = kHeight * FACTOR;  
     frame.size.width = kWidth * FACTOR;  
       
     UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];  
     UIImage *myImage = [UIImage imageNamed:@"checkmark"];  
     [button setBackgroundImage:myImage forState:UIControlStateNormal];  
       
     [button addTarget:self action:@selector(showActionSheet:) forControlEvents:UIControlEventTouchUpInside];  
     button.frame = frame;  
     button.tag = i+1;  
        
     [self.scrollView addSubview:button];  
   }  
 }  

*( NOT A Good algorithm ) but just for example



Finally to layout codes with format in Blogger I used -
http://codeformatter.blogspot.com/

Sunday, August 4, 2013

Discover and organize Github alternate repositories

Do you use lots of framework in your project. If so you must be using Cocoapods.
But what if you want to find alternate solution to your current framework .

Try Gitrep.

For example if you want to try RestKit as framework but explore alternate framework then
go to this link
http://gitrep.com/users/RestKit/repos/RestKit
It will show u other similar alternate framework.

But if you want to learn RestKit follow this stackover flow answer.

And for facebook's popular framework three20 - which no longer supported has alternate nimbus

http://gitrep.com/users/facebook/repos/three20

http://gitrep.com/

Happy Discovering :)

Xcode plug-in to autocomplete name for image and Color



Can't remember whether that image you just added to the project was called button-separator-left or button-left-separator? Now you don't have to, because this will autocomplete your imageNamed: calls like you'd expect. Just type in [ NSImage imageNamed: or [ UIImage imageNamed: and all the images in your project will conveniently appear in the autocomplete menu.