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.

Friday, December 17, 2010

Let get start work on blog agian.

Hi friends,

Lets start exploring cocoa. From a couple of months I was departed from my blog..
And the phenomenon of learning was stopped during that period. I have a few things to share
with you.

Wednesday, August 18, 2010

Installing an Application for Testing Over iPhone/iPod



The developer sends you an archive containing two files: the application and a provisioning profile.
You need to install both files into iTunes to be able run the application on your device.
After opening the archive:
  1. Drag the provisioning profile (the file with the .mobileprovision extension) to the iTunes Library group.
  2. Drag the application (the file with the .app extension) to the iTunes Library group.
    The application appears in the Applications list.
  3. Sync your device.
    If the version of iPhone OS on your device is earlier than the test application can run on, you need to update your device with the current release of iPhone OS.

Tuesday, July 27, 2010

UIView With Rounded corners

For Rounded Corners of UIView You Can use the following Code..
But you have to import first....
#import <QuartzCore/QuartzCore.h>

aView.layer.cornerRadius=8.0;
aView.layer.masksToBounds=YES;


cheers
Mandeep

Thursday, June 3, 2010

PDF Reader on iphone and ipad

hey
I found that beginner face problem in my previous post related to the pdf file reading on the iphone / ipad. so I upload a sample application and you can download from here.

PDFReader.zip

please ask feel freely any thing regarding iphone/ipad programming

Thursday, May 6, 2010

Colored UITabBar / Custom Color to UITabBar

hi friends
there is a simple way to set color of your UITabBar

CGRect frame = CGRectMake(0.0, 0, 320.0, 48);
UIView *v = [[UIView alloc] initWithFrame:frame];

[v setBackgroundColor:[[UIColor alloc] initWithRed:1.0 green:1.0 blue:0.0 alpha:0.6]];

[tabBar insertSubview:v atIndex:0]; //tabBar is object of your UITabBar

Thursday, April 22, 2010

How to show PDF document/file on iphone / ipad.

Hi Guys.
Simple way to show pdf file on UIView. You just use the following class and alloc your UIView with PDFView class.
PDFView.h
#import
@interface PDFView : UIView {
CGPDFDocumentRef pdf1;
int pageNo;
}
-(void)drawInContext:(CGContextRef)context pno:(int)pageNo;
-(int)numberOfPages;
@end

PDFView.m

#import "PDFView.h"

@implementation PDFView

- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
CFURLRef pdfURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("iphoneos.pdf"), NULL, NULL);
pdf1 = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
CFRelease(pdfURL);
self.backgroundColor = [UIColor whiteColor];
self.opaque = YES;
}
return self;
}

- (void)drawRect:(CGRect)rect {
[self drawInContext:UIGraphicsGetCurrentContext()];
}
-(int)incrementPage :(int)no{
pageNo =no;
return pageNo;
}

- (void)dealloc {
[super dealloc];
}
-(void)drawInContext:(CGContextRef)context{
// before we start drawing.
CGContextTranslateCTM(context, 0.0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
// Grab the first PDF page
CGPDFPageRef page = CGPDFDocumentGetPage(pdf1, pageNo);
// We're about to modify the context CTM to draw the PDF page where we want it, so save the graphics state in case we want to do more drawing
CGContextSaveGState(context);
// CGPDFPageGetDrawingTransform provides an easy way to get the transform for a PDF page. It will scale down to fit, including any
// base rotations necessary to display the PDF page correctly.
CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFCropBox, self.bounds, 0, true);
// And apply the transform.
CGContextConcatCTM(context, pdfTransform);
// Finally, we draw the page and restore the graphics state for further manipulations!
CGContextDrawPDFPage(context, page);
CGContextRestoreGState(context);
}
//Returns Number of Pages
-(int)numberOfPages{
CFURLRef pdfURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("iphoneos.pdf"), NULL, NULL);
pdf1 = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
int noOfPage =CGPDFDocumentGetNumberOfPages((CFURLRef)pdf1);
return noOfPage;
}
@end
And your Viewcontroller class, just implement the following code

UIView *myView=[[PDFView alloc]initWithFrame:rect];
int totalpage = [myView numberOfPages];
[myView drawRect:CGRectMake(0, 0, rect.size.width, rect.size.height)];
[self.view addSubView:myView];

Monday, April 5, 2010

Transparent Background on iPhone UIWebView

Simple solution to creating a UIWebView with a transparent background:

  • set your background color of the UIWebView to clear
  • set the css for the body to background-color: transparent
  • here's the bugger... set the opaque property of the UIWebView to NO
Code
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 310,450)]; self.bounds.size.height-60)];
[webView setBackgroundColor:[UIColor clearColor]];
[webView setOpaque:NO];
[self.view addSubview:webView];
cheers

Japji Sahib on iphone

Past week, i upload new application on the app store. Japji Sahib reader.






http://itunes.apple.com/in/app/japji-sahib-punjabi/id364602780?mt=8

Monday, March 22, 2010

Last Week another release on itunes

Last friday, me and amit did release the you and me 'nought & cross' on the itunes stores.
As amit came in team, the speed of development should accelerate.

Wednesday, March 17, 2010

How to get Iphone device id for Provisioning.

First Way

1) Connect your iPhone/iPod Touch to your computer if it isn’t already connected
2) Launch iTunes
3) Click on the text “Serial Number:” in the “iPhone” section of the Summary tab.
4) The serial number will be replaced with the Identifier.
5) And U will get the 40 digit Identifier.

Second Way
1) Install the iPhone Configuration Utility if it is not already installed. [http://www.apple.com/support/iphone/enterprise/]
2) Connect your iPhone/iPod Touch to your computer if it isn’t already connected
3) Launch the iPhone Configuration Utility
4) If your iPhone/iPod Touch is not automatically selected – click on it’s entry at the bottom of the left-hand column
5) At the top of the screen, click on the “Export” button
6) In the save dialog box that opens, change the “Export type:” to “Device UDIDs”

Monday, March 8, 2010

Earn smile and kcard Magic with new looks is now available on App store

Hi guys
kCard magic is now released with new look. and After new look, in first day downloads is more than 250.

last week earn smile is also released on the app store.


downloads







Friday, February 19, 2010

kTrivia Geography and ithishome released.

hi Guys,
Past 2 weeks great for me. My developed two more applications release on the itune store.
Hope fully by end of this month, we will release two more games on itune store.
Thanks

kTrivia Georaphy


ithishome