Friday, February 28, 2014

Compressing Photos/UIImage maintaining Aspect Ratio in iPhone App

Normally, the pictures taken from iPhone camera are high resolutions and it ranges from 1-4 MB in size. When our app needs to send these size of images to the server, upload may take long time which  breaks down the overall app's performance. So in this section, I am sharing a short and sweat objective-c method which will compress original image in iPhone , makes image size small and also the aspect ratio is maintained.
As for my test, 2048*1536 (930 kb) size image  is compressed to 600*450 (169 kb) image and 2448*3264 (2.5 mb) size image is compressed to 600*800 (230 kb) image using the following objective-c method:

- (UIImage *)compressImage:(UIImage *)image {
    float actualHeight = image.size.height;
    float actualWidth = image.size.width;
    float maxHeight = 800.0; //new max. height for image
    float maxWidth = 600.0; //new max. width for image
    float imgRatio = actualWidth/actualHeight;
    float maxRatio = maxWidth/maxHeight;
    float compressionQuality = 0.5; //50 percent compression
   
    if (actualHeight > maxHeight || actualWidth > maxWidth){
        if(imgRatio < maxRatio){
            //adjust width according to maxHeight
            imgRatio = maxHeight / actualHeight;
            actualWidth = imgRatio * actualWidth;
            actualHeight = maxHeight;
        }
        else if(imgRatio > maxRatio){
            //adjust height according to maxWidth
            imgRatio = maxWidth / actualWidth;
            actualHeight = imgRatio * actualHeight;
            actualWidth = maxWidth;
        }
        else{
            actualHeight = maxHeight;
            actualWidth = maxWidth;
        }
    }
    NSLog(@"Actual height : %f and Width : %f",actualHeight,actualWidth);
    CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
    UIGraphicsBeginImageContext(rect.size);
    [image drawInRect:rect];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    NSData *imageData = UIImageJPEGRepresentation(img, compressionQuality);
    UIGraphicsEndImageContext();
   
    return [UIImage imageWithData:imageData];
}

* depending on your compressionQuality , the image size and quality varies, and its value ranger from 0 to 1.

Tuesday, July 16, 2013

Programmatically detecting isDevice iPhone 5 ?


Define global  condition as below in your global classes:

#define IS_IPHONE_5 ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )

Used C functions:
DBL_EPSILON = will give the smallest value that will make a difference when adding with one.  Smallest number such that 1.0 + DBL_EPSILON  != 1.0.
fabs = gives absolute value of x (a negative value becomes positive, positive value is unchanged).

Now simply you can detect iPhone 5 as :
if(IS_IPHONE_5){
            NSLog(@"I am iPhone 5");
}
else {
              NSLog(@"I am not iPhone 5");

}

Monday, July 15, 2013

Auto Search/Auto Complete using UITextField as SearchBar for iOS app


After a long gap, I made a time off  from my regular stuffs to write here few things. This time I choosed a topic  “Auto Search/Auto Complete” ,. You guyz already knew about this feature , if not, then auto search/Auto complete is the process of searching when you type some character in Search field. Auto search simply detects each of the character you type and starts searching. Moreover, When a user is entering data into a text field, it’s often nice to have the ability to auto complete with custom values based on what the user is entering, saving their time.

Auto Search  the name,  always sounds complicated  . Even I always thought doing auto search features in iOS app must be complicated but I was wrong . It is not hard as it sounds, and how I figured it out , I am explaining here with simply using UItextField and its native method.

Here are the step by step guidelines :

1.     First thing you need to create is UITextField which works as a search bar and UITableView for displaying your search results. And another thing is data source (Array/Dictionary) which has a collection of data from where we need to search  based on the name/strings which user types in text field.
2.     You can play with UItableView  in your own way. You simply can hide it first and when starts searching and finds result , you can unhide the table and reload the data. OR simply you can only add table view when search starts and remove it when we are done with the selection.
Here, I am using Hidden property of UItableView.
3.     Create UITextField , define <UITextFieldDelegate> in you .h file

Tuesday, April 23, 2013

Creating Watermarked Images from iOS app

Hello Guyz, In this section i will give you a bunch of code for creating a watermarked images. For example: Images with copyright text on top of it.  It sounds difficult but believe me, I have a really simple solution for you. In this part,  I am only merging  two of the images (one is watermark image and another is the image in which you want to put watermark) and hence making them one. So before we proceed, remember you should have watermark image and main image(picture) in your project resources.

-(UIImage *) generateWatermarkForImage:(UIImage *) mainImg{
      UIImage *backgroundImage = mainImg;
    UIImage *watermarkImage = [UIImage imageNamed:@"watermark.png"]; 

Wednesday, February 27, 2013

NSDocumentsDirectory and iCloud issue :preventing files in a App's Documents Directory being synced to iCloud

Many of you guys use app's  "Documents Directory" to store your files(image,video,pdf,music etc) in iOS app and being an iOS developer, it's obvious that you use documents directory since for each app,its the best way to store your files on the device permanently ,so that your app can  function properly in offline mode too.
However, if you are trying to store large number of files (obvious referring both in quantity and size) in app's documents directory, then i will say STOP & WAIT!!! 

- "STOP" because your app gonna be rejected by Apple because according to Apple's latest iOS Data Storage Guidelines : "Since iCloud backups are performed daily over Wi-Fi for each user’s iOS device, it’s important to ensure the best possible user experience by minimizing the amount of data being stored by your app." In summery i will say there are two points, every files in NSDocumnetsDirectory will be synced to user's iCloud and another is,if file sizes stored in NSDocumnetsDirectory are large then Apple will reject it since that causes the slow down on syncing process as iCloud-device syncs on daily basis.
-"WAIT" because i have a solution for it.
As pointed above if you are going to save files in NSDocumentDirectory then it will be back-up to iCloud,that means any thing you store in documents folder, will be synced to user's iCloud and will be publicly available. So if your files stored in documents directory  makes no sense by being public then you don't have to worry about anything(unless its size is bigger), but if your file  stored there are large in size and  can not be public,or i say if these files are only intended just for the scope of your app then you must have to do extra work to prevent from being synced to iCloud.

There are two solutions for it :

Monday, February 25, 2013

Sharing your app via Facebook and Twitter using Social Framework

Hello Guyz, in this section i will be describing about how we can use new "Social Framework" for sharing our app(tweet+status) from our iOS apps. It's really easy to deal with but, we should keep in mind that Social framework is only available from iOS 6 and later . Here, we will be only focusing on how to share our app , along with how to tweet and post a status from our iOS app.



1. Add "Social.framework" in your project.
2. Include  #import <Social/Social.h> to your .h file
3. Now, in your sharing method :

Tuesday, February 5, 2013

Ad-Hoc Distribution of iOS Apps - Simple Solution

If you are searching for a blog that describes the better way to do a ad hoc distribution of your iOS apps, I simply prefer you to go through : http://www.diawi.com/ 
This is the perfect way of distributing and installing iOS apps on real device. We don't need to sync app  through iTunes and even we do not need any computers, we can simply download it on our device and install it.

Note : Before proceeding, first make .ipa or .app file of your project from Xcode since in this section i am not talking about how to make .ipa/.app file from xcode but i am talking about how to send your apps to the end test users in a simplest and efficient way.

Best of Luck !!!

Monday, January 28, 2013

Few tips on ARC Compatibility - enabling/disabling your project ARC

Most of you guyz already know what really  ARC means, but for rest of you which are unknown about it, ARC means Automatic Reference Counting, is a feature of the new LLVM 3.0 compiler and it completely replaces the manual memory management that means we do not have to worry about memory releases of the objects we create. ARC has removed the use of retain, release, autorelease keywords and it acts like a garbage collector. ARC will take care of all the memory issues, and we developer do not have to worry about it any more.


PROBLEM :
However, since ARC is a new feature in iOS development , we may find compiling errors regarding memory keywords  while we want to mix up old projects with new ARC enabled ones, or  error occurs when we want to use ARC disabled  third party libraries to our ARC enabled project. Just like in pic:


Friday, January 25, 2013

Sending e-mail in background from iOS apps using SMTP gmail account

The iOS SDK has made it really easy to send email using the built-in APIs. With a few line of codes, you can launch the same email interface as the stock Mail app that lets you compose an email. You can pop up mail composer form , write message and can send plain mail or file attached mail using MFMailComposeViewController class. For more info : Sending e-mail from your iOS App

But, in this section what i am going to explain is about sending emails without showing the mail composer sheet ie. sending emails in background. For this feature, we can not use iOS native MFMailComposer class because it does not allow us to send emails in background instead it pop ups the mail composer view from where user have to tap "send" button , so for this section i am going to use  SKPSMTPMessage Library to send emails in background, however email account has to be hardcoded on this method.

Limitations :
1. sender/receiver email address has to be hardcoded or you have to grab it using some pop up form in your app where user inputs sender/receiver email address. In addition, sender account credentials has to be also hardcoded since there is no way we can grab it from device settings.

Method :
1. Import CFNetwork.framework to your project.
2. Include     #import "SKPSMTPMessage.h"
                    #import "NSData+Base64Additions.h" // for Base64 encoding
3. Include <SKPSMTPMessageDelegate> to your ViewController
4.  Download SKPSMTPMessage library from  
                                             https://github.com/jetseven/skpsmtpmessage
5. Drag and Drop "SMTPLibrary" folder you have downloaded to your project.

  Before proceeding, let you know that i am using sender/receiver email address and sender password hardcoded in the code for this example.But, you may grab this credentials from user, allowing them to input in some sort of forms(using UIViews).

Friday, January 18, 2013

Integration of File Sharing from your App to iTunes

Hey guyz, in this section i will be explaining about how we can share app's files which are stored in its document directory  via itunes, say, accessing app's document directory. For example, lets say some app named "testApp" stores bunch of files in its documents folder which are downloaded from web, now we may want to see those files in our desktop. So for file sharing, iOS 4 & later have a great new feature called File Sharing that provides a convenient way for users to transfer files between their computer and your app.

Its really a simple step and it goes like this.......
- To enable File Sharing in your app, you simply set the boolean flag UIFileSharingEnabled in your info.plist. Or , some of you may find Application supports iTunes file sharing flag in your info.plist. Just set flag to YES.


After that, iTunes will display anything you save to the Documents directory in your app to the user, when they go to the “Apps” page in iTunes like this :
Note : One thing, you must keep in your mind is that only the files that are stored in your app's documents directory can be seen and shared!!! For storing files in documents directory, please have a look at :  Handling NSDocumentDirectory of iOS App

That's all from Xcode side, Now for more details on  File sharing features : http://support.apple.com/kb/HT4094#

Thursday, January 17, 2013

Checking Internet Connection in iOS Apps

In this section, i will be describing about how we can check internet connectivity in iOS apps. For this kind of task, Apple has provided a very helpful sample reachability class . So, we will be using that class to make it working on our apps. First , grab the reachability sample code from: http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html

Now, you don't have to ho through all the codes in sample app, just follow these few steps to check internet connection in our app :

  1. Add the SystemConfiguration.framework to your project.
  2. Add the files Reachability.h and Reachability.m only from the Reachability sample code you just downloaded to your project.
  3. Add the following code in the implementation file where you need to test the Internet connection.    

Thursday, December 20, 2012

Having problem on creating .ipa file from Xcode's "Product -> Archive" or "Build & Archive" method ?

                 Creating an IPA is done in a simple way from your Xcode : Product -> Archive (previously Build & Archive). After the Archive operation completes, go to the Organizer, select your archive, select Share and in the "Select the content and options for sharing:" pane set Contents to "iOS App Store Package (.ipa) and Identity to iPhone Distribution (which should match your ad hoc/app store provisioning profile for the project).
It's a simple stuff to do but BANggggg... You might be in trouble if you have been using some other static library, third party library, other xcode project files in your project. You might have following issue that disables your .ipa file selection :
 “No Packager exists for the type of archive and This kind of archive cannot be signed."

Wednesday, December 19, 2012

Opening iOS Apps from Browser or any other source using URL Scheme in iOS Devices

In this section, i will be describing about how to open up an app in iOS device either from a Browser or from any other application present in iOS devices.

First thing you need to do is to register a URL scheme  in to device which is done in your app's info.plist file. URL Scheme will be your key to open up your app from browser or any other app. Here are the step by step procedure :
First open up your info.plist
Step 1. Right-Click and “Add Row”
screen-capture.png

Wednesday, October 3, 2012

"Pull Down To Refresh" integration for updating data in UITableViews

Hello Guyz , in this section we will be talking about "Pull Down To Refresh" integration for updating your data in UITableView. This kind of effect can be seen in  facebook app, where we  pull down the view and it refreshes/updates the facebook feeds. In the similar way, in this section i will write a bunch of codes that basically do is: when we pull down the UITableView, it will updates its datasource and reload the table section. Here, is the example screen that will help you to understand about this effect more wisely.
download and add this dropdown image to be used in project named updateArrow.png

Tuesday, October 2, 2012

Rate/Review apps in iTuneStore from inside iOS application

Hello Guyz, in this section i will describe you, how we can write a review or rate an app in iTuneStore from inside iOS Application by writing few lines of code. The example i am showing here will directly open up the iTuneStore review section of your app  in your device (to be noted is that the bunch of code i am writing here will only work on actual device.)

-(IBAction) rateAndReviewInItuneStore:(id)sender{
 NSString* url = [NSString stringWithFormat: @"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%@",AppID];
     [[UIApplication sharedApplication] openURL: [NSURL URLWithString: url ]];

}
Here, AppID = your Apple ID in your iTuneStore , can be found inside your app  in iTuneStore and under "App Infromation" section of your app (9 digit numbers).

"Follow us on Twitter" button integration in iOS Application

Hello Guyz, In this section i will show you the two different way to integrate "Follow us on Twitter" button from inside our iOS App. If you are a twitter user then you probably got what i am talking about. "Follow us" button is very popular in web apps, by integrating it we can directly follow some people or organization depending on the twitter screen name we choose to follow and in this section i will show you how we can integrate it from inside our iOS apps.

Method 1: Without using any API
 Without plugging into native twitter app or  using any other API in code, we could simple open a URL to do the job of Following some one in twitter.
-(IBAction)FollowUsOnTwitter:(id)sender {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://twitter.com/intent/user?screen_name=%@",TwitterAccountName]]];
}
Note : TwitterAccountName = your twitter account name you wish to follow, and it will open to follow that account in the browser.

Method 2: Using Twitter Framework for iOS 5 and later
  To be noted here is that Twitter framework is available  only for  iOS 5 and later version.
- First of all , add "Twitter.framework" and "Accounts.framework" to your project.
- now include #import <Accounts/Accounts.h> and #import <Twitter/Twitter.h> to your .h file.

Thursday, September 20, 2012

Moving Images/Objects around the screen using Touch function in iOS app

Hi Guyz, in this section i will give you the idea of moving your objects(Image in our case) in the screen using Touch function. In previous blog, we talked about the drag and drop method, where we were dragging some object from one position and dropping it to  another one but in this section we are only going to reposition/move the object in the screen.So basically in this section, we will see how the multiple images moved using touch function. Lets get started !!!!

Create multiple (say 4 in our case) UIImageView in your viewcontroller and connect it to the IBOutlet and assign them with different images.
In your .h file ;
  @property(nonatomic,retain) IBOutlet UIImageView *imageView1;
  @property(nonatomic,retain) IBOutlet UIImageView *imageView2
  @property(nonatomic,retain) IBOutlet UIImageView *imageView3;  
  @property(nonatomic,retain) IBOutlet UIImageView *imageView4; 
In your .m file,
  @synthesize imageView1,imageView2,imageView3,imageView4;
Now,use Touch delegate method as :
  - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
       // get touch event
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];
     if ([touch view] ==
imageView1) { // If touched view is imageView1 , then assign it its new location
               
imageView1.center = touchLocation;
    }
       else if ([touch view] ==
imageView2) {
          
imageView2.center = touchLocation;
    }
    else if ([touch view] ==
imageView3) {
              
imageView3.center = touchLocation;
    }
    else if ([touch view] ==
imageView4) {
              
imageView4.center = touchLocation;
    }
}

 So that's it!! so simple to move objects around the screen in iOS apps.


Tuesday, September 18, 2012

Draging and Droping objects in iOS App

Hi Guyz, in this section i will  describe you how to drag any particular views/objects and dropping it somewhere else. This is the nice feature  mostly seen in web apps, but here i will be detailing how to use this features in iOS Apps. In this demo, we will be changing the background color of UIView (where we will be dropping objects) depending on the dragged object's color and i will also give you a hint to change the position(repositioning it) of dragged object's as a result of Drag and Drop.
Lets get started !!!!

First design your  ViewController.xib file  as in figure with four dragging objects(here,UIImageView) and one UIView (as dropping target view). Change the background color of all 4 UIImageViews.
Now in .h file,
   // connect target UIView in Interface Builder
@property (nonatomic, strong) IBOutlet UIView *dropTargetView;
     // define temp UIImageView for view being dragged
@property (nonatomic, strong)  UIImageView *dragObjectView; 
    //distance between the actual touch point and the upper left corner of the dragObject
@property (nonatomic, assign) CGPoint touchOffset;
  // drag object's original position  in screen
@property (nonatomic, assign) CGPoint homePosition;

Monday, September 17, 2012

Creating PDF file from simple Texts/NSStrings/UIImages in iOS App

Hi Guyz, In this section i will write you a bunch of custom methods that can be used for generating PDF files from your simple texts and NSStrings in iOS app. In this section, we will be using core Graphics functions of Objective-C, No frameworks are used. You can have your own design customization  beside what i have designed here. I hope this blog will help you to start generating PDF as per your requirements. Lets start coding!!!

Lets define some variables and constants in .h file:
    #define kBorderInset            20.0
    #define kBorderWidth            1.0
    #define kMarginInset            12.0
    #define kLineWidth              1.0
    CGSize pageSize;

-(IBAction)generatePdfButtonPressed:(id)sender; //UIButton method for generating PDF
Now, in .m file : (lets have some custom methods)
- (void) drawBorder{
    /***get the current context, select a color for the border, specify a rect for the border, which has an inset of 20 pixels, and then just stroke the rect using normal Core Graphics.***/
    CGContextRef    currentContext = UIGraphicsGetCurrentContext();
    UIColor *borderColor = [UIColor brownColor];
    CGRect rectFrame = CGRectMake(kBorderInset, kBorderInset, pageSize.width-kBorderInset*2, pageSize.height-kBorderInset*2);
    CGContextSetStrokeColorWithColor(currentContext, borderColor.CGColor);
    CGContextSetLineWidth(currentContext, kBorderWidth);
    CGContextStrokeRect(currentContext, rectFrame);
}

Thursday, September 13, 2012

Bridging between JavaScript & Objective-C for Hybrid iOS Apps

Hi Guyz, in this section i will write about the bridging between the native Objective-C code with the web portion(JavaScript/HTML) code. The iOS hybrid application delivers a native experience on iOS devices by wrapping the mobile Web storefront with a native shell. The native shell elements are coded using the iOS Software Development Kit (SDK), while the storefront is accessed using the mobile Web interface. That generally means  hybrid app is a combination of web app + native iOS features. We use UIWebView for loading the webapp (linking URL) and we can have our own iOS feature included with it. So, In this section, i will be describing about how to call native Objective-C method from particular button in web portion and vice versa.

Call Javascript function from Objective-C

  // In your Javascript files:
    function myJavascriptFunction () {
        // Do whatever your want!
        }
       // -----------------------------------
       // And in your Objective-C code:
    // Call Javascript function from Objective-C:

    [webViewObject stringByEvaluatingJavaScriptFromString:@"myJavascriptFunction()"];

Call Objective-C function from Javascript

// In Objective-C
    - viewDidLoad {
        webView = [[UIWebView alloc] init];
        // Register the UIWebViewDelegate in order to shouldStartLoadWithRequest to be called (next function)
        webView.delegate = self; 
    }