Wednesday, November 21, 2012

Apple Script check particular file exists or not

Following code helps you for finding particular file using apple script.


set msg to "no"
tell application "Finder"
if exists POSIX file "/usr/lib/libc++.dylib" then
set msg to "yes"
end if
end tell

display dialog msg

Friday, June 15, 2012

Facebook and Twitter integration in your iOS app

Hi Guys, Today I am showing you, how easily you can integrate Facebook and Twitter in your iOS application.

Let's first start with Facebook integration. For Facebook you have to register your app and you can register your app from here. Create you app there and enter basic information of your app as shown in below picture.  And note down your app Id.

Register your Facebook app

After registering app next step is to download latest Facebook iOS SDK from GitHub repository from here. Now move to Xcode. In your Xcode project add Facebook src files which you which download from GitHub repository. And Facebook integration is as below.

MDAppDelegate.h


#import <UIKit/UIKit.h>
#import "Facebook.h"

@class MDViewController;

@interface MDAppDelegate : UIResponder <UIApplicationDelegate,FBSessionDelegate, FBDialogDelegate>{
    
}

@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, retain) Facebook *facebook;

@property (strong, nonatomic) MDViewController *viewController;

-(void)shareOnFB;

@end



MDAppDelegate.m



#import "MDAppDelegate.h"

#import "MDViewController.h"

@implementation MDAppDelegate

@synthesize window = _window;
@synthesize viewController = _viewController;
@synthesize facebook;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.viewController = [[MDViewController alloc] initWithNibName:@"MDViewController" bundle:nil];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [facebook handleOpenURL:url]; 
}

- (void)shareOnFB {
    self.facebook = [[Facebook alloc] initWithAppId:@"YOUR_APP_ID" andDelegate:self];
    
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@"FBAccessTokenKey"
        && [defaults objectForKey:@"FBExpirationDateKey"]) {
        self.facebook.accessToken = [defaults objectForKey:@"FBAccessTokenKey"];
        self.facebook.expirationDate = [defaults objectForKey:@"FBExpirationDateKey"];
    }
    
    
    if (![facebook isSessionValid]) {
        NSArray *permissions = [[NSArray alloc] initWithObjects:
                                @"user_likes"
                                @"read_stream",
                                nil];
        [self.facebook authorize:permissions];
        // [permissions release];
    }
}

#pragma mark Facebook Delegate Method

- (void) fbDidLogout {
    // Remove saved authorization information if it exists
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@"FBAccessTokenKey"]) {
        [defaults removeObjectForKey:@"FBAccessTokenKey"];
        [defaults removeObjectForKey:@"FBExpirationDateKey"];
        [defaults synchronize];
    }
}

- (void)fbDidLogin {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[facebook accessToken] forKey:@"FBAccessTokenKey"];
    [defaults setObject:[facebook expirationDate] forKey:@"FBExpirationDateKey"];
    
    [defaults synchronize];
    
    NSLog(@"facebook Integration : ");
    
    NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   @"YOUR_APP_ID", @"app_id",
                                   @"http://mandeepdhiman.blogspot.com", @"link",
                                   @"https://dl.dropbox.com/u/10137094/fb.png", @"picture",
                                   @"MyTestApp", @"name",
                                   @"Reference Documentation Text", @"caption",
                                   @"Facebook test integration from my App...", @"description",
                                   nil];
    
    [self.facebook dialog:@"feed" andParams:params andDelegate:self];
    
}


@end

One more thing you have to add in your application plist file "URL Schemes" for Facebook integration.  URL Schemes item value is 'fbYOUR_APP_ID'. As shown in image below.



Now we can move to Twitter Integration part. For twitter you have integrate your Twitter framework to you project and rest of the twitter integration is as below.

MDViewController.h

#import <UIKit/UIKit.h>
#import <Twitter/Twitter.h>

@interface MDViewController : UIViewController{
    
}
- (IBAction)shareOnTwitter:(id)sender;

@end

MDViewController.m

#import "MDViewController.h"
#import "MDAppDelegate.h"

@implementation MDViewController

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

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

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

#pragma mark -

- (IBAction)shareOnTwitter:(id)sender {
    
    TWTweetComposeViewController *twitter = [[TWTweetComposeViewController alloc] init];
    
    [twitter addImage:[UIImage imageNamed:@"icon.png"]];
    [twitter addURL:[NSURL URLWithString:@"http://mandeepdhiman.blogspot.in"]];
    [twitter setInitialText:@"MyTestApp"];
    
    
    [self presentModalViewController:twitter animated:YES];
    
    twitter.completionHandler = ^ (TWTweetComposeViewControllerResult result){
        
        if (result == TWTweetComposeViewControllerResultDone) {
            NSLog(@"Tweet composition completed.");
        }else if ( result == TWTweetComposeViewControllerResultCancelled){
            NSLog(@"Tweet Composition was canceled.");
        }
        [self dismissModalViewControllerAnimated:YES];
    };
    
}

- (IBAction)shareFBBtnAction:(id)sender; {
    
    MDAppDelegate *appDelegate = ((MDAppDelegate *) [UIApplication sharedApplication].delegate);
    [appDelegate shareOnFB];
}

@end


App working video




You can download demo project from here

References
https://developers.facebook.com/docs/mobile/ios/build/
http://developer.apple.com/library/ios/#documentation/Twitter/Reference/TwitterFrameworkReference/_index.html

Sunday, October 16, 2011

Crash Reporter for iOS


Hi friends,
Today I google for find out easiest way to get information about crashes, when they occur in iOS application. Apple provides a mechanism for it: iOS records crash logs on device, when you sync it with iTunes the logs are copied to the user's computer. This make lots of work for user, So I start to find out its alternative.

At end I am able to found out a alternative of it. PLCrashReporter is "Plausible CrashReporter" is open source library develop Landon J Fuller. "It not just only creates a crash logs for you, But also makes it easy to tell the user about it the next time they start the application, and ask them if they'd like to email or upload  the report back to developer"

Its working video



To integrate PLCrashReporter you have to follow the following steps.

  1. Download the PLCrashReporter source release.
  2. Navigate to the CrashReporter-iPhoneSimulator Target. Under the Build Settings: a) set "Perform Single-Object Prelink" to "No", b) set "Mach-O Type" to "Static Library".
  3. Select CrashReport-iPhoneSimulator : [IOS simulation (ie iPhone 4.3 Simulator)] and click build.
  4. Navigate to your build directory for the PLCrashReporter. For me, it was /Users/username/Library/Developer/Xcode/DerivedData/CrashReporter-(random characters)/Build/Products/Debug-iphonesimulator.
  5.  Copy the libCrashReporter-iphonesimulator.a from the build directory in step 4 to the iphone application project directory you want to add the crash reporter to.
  6. Open the your iphone application project in xcode.
  7. Download the PLCrashReporter binary release and extract the framework to a local directory.
  8. Add the CrashReporter framework to your project.
  9. Following the same procedure as step 9, add the libCrashReporter-iphonesimulator.a static library to the "Link Binary with Libraries" section of the build phases. No *.framework directory is needed when adding a static library.
  10. 10.  Review the "Link Binary with Libraries" in the Target. Make sure the libCrashReporter-iphonesimulator.a is listed above the CrashReporter framework. You can drag and drop to reorder.
Coding part.
// from UIApplicationDelegate protocol
- (void) applicationDidFinishLaunching: (UIApplication *) application {
    PLCrashReporter *crashReporter = [PLCrashReporter sharedReporter];
    NSError *error;

    /* Check if we previously crashed */
    if ([crashReporter hasPendingCrashReport])
        [self handleCrashReport];

    /* Enable the Crash Reporter */
    if (![crashReporter enableCrashReporterAndReturnError: &error])
        NSLog(@"Warning: Could not enable crash reporter: %@", error);
}

/**
 * Called to handle a pending crash report.
 */
- (void) handleCrashReport {
    PLCrashReporter *crashReporter = [PLCrashReporter sharedReporter];
    NSData *crashData;
    NSError *error;

    /* Try loading the crash report */
    crashData = [crashReporter loadPendingCrashReportDataAndReturnError: &error];
    if (crashData == nil) {
        NSLog(@"Could not load crash report: %@", error);
        goto finish;
    }

    /* We could send the report from here, but we'll just print out
     * some debugging info instead */
    PLCrashReport *report = [[[PLCrashReport alloc] initWithData: crashData error: &error] autorelease];
    if (report == nil) {
        NSLog(@"Could not parse crash report");
        goto finish;
    }

    NSLog(@"Crashed on %@", report.systemInfo.timestamp);
    NSLog(@"Crashed with signal %@ (code %@, address=0x%" PRIx64 ")", report.signalInfo.name,
          report.signalInfo.code, report.signalInfo.address);

    /* Purge the report */
finish:
    [crashReporter purgePendingCrashReport];
    return;
}
Sample Code CrashReportHandling

Reference :



Tuesday, May 10, 2011

How to Make Custom Folder Icon in MAC

Hi 
I am sharing my first simple video tutorial






Tuesday, May 3, 2011

Email Validation in Objective C

-(BOOL)emailValidation:(NSString *)email {
    BOOL result;
    //checking email validation
    NSString *emailRegEx = @"[A-Z0-9a-z._-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
    //Valid email address
    if ([emailTest evaluateWithObject:email] == YES){
        NSLog(@"Valid email address");
        result=NO;
    }else{
        NSLog(@"Invalid email address");
        result=YES;
    }
    return result;
}

MD5 in Objective C

Just Import  CommonCrypto/CommonDigest.h and following method returns md5 string.

 #import <CommonCrypto/CommonDigest.h>

- (NSString *)convertIntoMD5:(NSString *) string{
    const char *cStr = [string UTF8String];
    unsigned char digest[16];

    CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
   
    NSMutableString *resultString = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
   
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [resultString appendFormat:@"%02x", digest[i]];
    return  resultString;
}

Thursday, December 23, 2010

Image upload in iphone

Hi
Today I am sharing image browse and image upload tutorial with you..
Call following method for uploading photo you need to pass image data and file name of your image
Other thing you need small php code for uploading..

  







Please make sure your upload directory have read/write permission 
<?php
$uploaddir = 'photos/';
$file = basename($_FILES['userfile']['name']);
$uploadfile = $uploaddir . $file;
         if(move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)){
         echo "YES";
         }else{
         echo "NO";
         }
?>


- (NSString *)uploadImageFunction:(NSData *)imageData filename:(NSString *)filename{
   
    // Please Specify your php script Url here
     NSString *urlString = @"http://127.0.0.1/iphone/uploader.php";
   
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
     
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
   
    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n",filename]] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:body];
   
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    return (returnString);
}
you can download zip and php script from here.