Sunday, October 21, 2012

Dropbox Integration in IOS


Requirements:
  1. You need the 4.0 version of the iPhone SDK. The version of your XCode should be at least 3.2.3.
  2. You need to have registered as a Dropbox application with mobile access. You should have a consumer key and secret.
  3. You need to download the dropbox sdk

A. Adding DropboxSDK to your project

  1. Open your project in Xcode
  2. Navigate to where you uncompressed the SDK and drag the DropboxSDK.framework folder into your project in Xcode
  3. Make sure Copy items into destination group's folder is selected
  4. Press Add button
  5. Ensure that you have Security.framework and QuartzCore.framework added to your project. To do this in Xcode 4, select your project file in the file explorer, select your target, and select the Build Phases sub-tab. Under Link Binary with Libraries, press the + button, select Security.framework, and press Add. Repeat forQuartzCore.framework.

Your app key is also needed in YourProject-Info.plist file so the app can register for the correct url scheme. To do this, find the file under the Resources group in the left pane, right-click it and select Open As → Source Code. Replace the textAPP_KEY with your app's key. (e.g-db-xs9loltwb0mlu4p)..

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    DBSession * dbSession = [[[DBSession alloc]initWithAppKey:@"YOUR-App-Key" appSecret:@"Your-secret-Key
" root:kDBRootDropbox] autorelease];
       [DBSession setSharedSession:dbSession];
    }
Somewhere in your app, add an event to launch the Dropbox authentication process:-
- (void)didPressLink {
    if (![[DBSession sharedSession] isLinked]) {
        [[DBSession sharedSession] linkFromController:yourRootController];
    }
}
The DBRestClient class is the way to access Dropbox from your app once the user has linked his account.o add an instance variable in the .h file 
DBRestClient *restClient;
#import <DropboxSDK/DropboxSDK.h>

...

- (DBRestClient *)restClient {
   if (!restClient) {
      restClient =
         [[DBRestClient alloc] initWithSession:[DBSession sharedSession]];
      restClient.delegate = self;
   }
   return restClient;
}
You can list the files in folder you just uploaded 
[[self restClient] loadMetadata:@"/"];
if (metadata.isDirectory) {
- (void)restClient:(DBRestClient *)client loadedMetadata:(DBMetadata *)metadata {
      dropboxPath= metadata.path;
      for (DBMetadata *file in metadata.contents) {
          if (file.isDirectory) {            
  NSLog(@"folder name ...%@", file.filename);
            }
            else {
                NSLog(@"image...%@", file.filename);
             
            }
        } 
}
   
- (void)restClient:(DBRestClient *)client
    loadMetadataFailedWithError:(NSError *)error {

    NSLog(@"Error loading metadata: %@", error);
}

Download a file

[[self restClient] loadFile:dropboxPath intoPath:localPath]
To find out when the file download either succeeds or fails implement the following DBRestClientDelegate methods:
- (void)restClient:(DBRestClient*)client loadedFile:(NSString*)localPath {
    NSLog(@"File loaded into path: %@", localPath);
}

- (void)restClient:(DBRestClient*)client loadFileFailedWithError:(NSError*)error {
    NSLog(@"There was an error loading the file - %@", error);

create image grid on iOS



  - (void)viewDidLoad
{  

   myScroolView=[[scrollView alloc] init];
  [myScroolView setFrame:CGRectMake(self.view.frame.origin.x,self.view.frame.origin.x, self.view.frame.size.width , self.view.frame.size.height)];
   myScroolView.backgroundColor = [UIColor clearColor];
   myScroolView.userInteractionEnabled=YES;
   myScroolView.delegate=self;
    
    activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activityIndicator.frame = CGRectMake(self.view.frame.size.width/2, self.view.frame.size.height/2, 30, 30);
    [self.view addSubview:activityIndicator];
    activityIndicator.hidden = YES;
    
       // Do any additional setup after loading the view from its nib.
[self createGrid];
}



-(void)createGrid
{
    NSLog(@"createGrid");
   
        [self.view addSubview:myScroolView];
        
       
        int outer=[YourImageArray count]/4;
        int inner=4;
   
        outer=([YourImageArray count]/4 -outer)>0? outer :outer+1;
        [myScroolView setContentSize:CGSizeMake(1024.0f, (outer*80)+30.0f)];
        for (int i=0,t=0;i<outer;i++)
        {
            if (i == outer-1) {
                inner=[YourImageArray count]%4;
                
            }
            for (int j=0; j<inner; j++) {
                
                UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(j*231.0f+90.0f, i*231.0f+90.0f,231.0f,231.0f)];
                myImage.image = [UIImage imageWithContentsOfFile:[YourImageArray objectAtIndex:t]];
                myImage.tag = t;
                [myImage setUserInteractionEnabled:YES];
                [myScroolView addSubview:myImage];
                [myImage release];
                t++;
            }
             
        }
        
        
    [activityIndicator stopAnimating];

    
}

Tuesday, October 16, 2012

Create folder in document directory in iPhone


NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"YourFolderName"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder

Wednesday, October 10, 2012

Post Image and Message on Facebook in iPhone


- (void)PostToWall{

     facebook = [[Facebook alloc] initWithAppId:FB_APP_ID andDelegate:self];
    [facebook authorize:FB_PERMISSION_ARR];
}

- (void)postWall{

    NSData *imageData = UIImageJPEGRepresentation(YOURIMAGE, .1f);
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:facebook.accessToken, @"access_token",
                                   @"MESSAGE POST ON FB WALL", @"message", imageData, @"source", nil];
    [facebook requestWithGraphPath:@"me/photos" andParams:params andHttpMethod:@"POST" andDelegate:self];
   
}


#pragma mark -
#pragma mark Facebook Function
/**
 * Called when the user has logged in successfully.
 */
- (void)fbDidLogin {
    [self postWall];
}
- (void)fbDidNotLogin:(BOOL)cancelled{
NSLog(@"fbDidNotLogin");
}

// FBRequestDelegate

/**
 * Called when the Facebook API request has returned a response. This callback
 * gives you access to the raw response. It's called before
 * (void)request:(FBRequest *)request didLoad:(id)result,
 * which is passed the parsed response object.
 */
- (void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response {
NSLog(@"received response");
}

/**
 * Called when a request returns and its response has been parsed into
 * an object. The resulting object may be a dictionary, an array, a string,
 * or a number, depending on the format of the API response. If you need access
 * to the raw response, use:
 *
 * (void)request:(FBRequest *)request
 *      didReceiveResponse:(NSURLResponse *)response
 */
- (void)request:(FBRequest *)request didLoad:(id)result {

NSLog(@"request:.%@", request);

if ([result isKindOfClass:[NSArray class]]) {
result = [result objectAtIndex:0];
}
if ([[result allKeys] count] == 1) {
if ([[result allKeys] containsObject:@"id"]) {
            
UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"Notification" message:@"Wall Post Success!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[al show];
[al release];
}
}else {
       
}
};

/**
 * Called when an error prevents the Facebook API request from completing
 * successfully.
 */
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
NSLog(@"error...%@",[error localizedDescription]);
    
UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"Notification" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[al show];
[al release];
};

Send Email with Image Attcahment in iPhone


-(void)sendEmail
{
    
    
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    if (mailClass != nil)
    {
        if ([mailClass canSendMail])
        {
            [self displayComposerSheet];
        }
        else
        {
            UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"Error!!" message:@"Device not configured to send mail." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil ];
            [alert show];
            [alert release];
        }
    }
    
}

-(void)displayComposerSheet
{
    if(EmailViewControllerObj==Nil)
        EmailViewControllerObj = [[EmailViewController alloc] init];
    [_glView addSubview:EmailViewControllerObj.view];
    EmailViewControllerObj.view.backgroundColor=[UIColor clearColor];
    picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
    [picker setSubject:@""];
NSArray *toRecipients = [NSArray arrayWithObject:@"abc@xyz.com"];
    NSArray *ccRecipients = [NSArray arrayWithObjects:@"abc@xyz.com",nil];
[picker setToRecipients:toRecipients];
    [picker setCcRecipients:ccRecipients];
    
    
    NSData *myData = UIImagePNGRepresentation(YOURIMAGE);
    [myData writeToFile:@"emailImage.png" atomically:YES];

    [picker addAttachmentData:myData mimeType:@"image/png" fileName:@"emailImage.png"];
    
    
    // Fill out the email body text
    NSString *emailBody = @"Text on Email Body";
    [picker setMessageBody:emailBody isHTML:NO];
    
    
    [EmailViewControllerObj presentModalViewController:picker animated:YES];
    [picker release];
    
    
    
    
}

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Result: Mail sending canceled");
            break;
        case MFMailComposeResultSaved:
            NSLog( @"Result: Mail saved");
            break;
        case MFMailComposeResultSent:
        {
            // NSLog( @"Result: Mail sent");
            
        }
            break;
        case MFMailComposeResultFailed:
            NSLog( @"Result: Mail sending failed");
            break;
        default:
            NSLog( @"Result: Mail not sent");
            break;
    }
[EmailViewControllerObj dismissModalViewControllerAnimated:YES];
    [EmailViewControllerObj.view removeFromSuperview];
}

Wednesday, October 3, 2012

Add buttons on navigation bar


You need to add UIBarButtonItem instance to a UINavigationItem, not to a UINavigationBar. So you can do this as:
NSArray *buttonArray = [NSArray arrayWithObjects:logoButton, logoButton2, logoButton3, nil];
self.navigationItem.leftBarButtonItems = buttonArray;
If you want your buttons on the right, use rightBarButtonItems.