Category Archives: Apple

Handling Files in iOS

Hi All,

In Todays article we will see how we can handle files in Objective C.

The list of the methods used for accessing and manipulating files are listed below. Here you have to replace the FilePath1, FilePath2 and FilePath strings to our required full file paths to get the desired action.

NSFileManager *fileManager = [NSFileManager defaultManager];
 //Get documents directory
 NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains
 (NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];
 if ([fileManager fileExistsAtPath:@""]==YES) {
           NSLog(@"File exists");
 } 

Comparing two file contents

 if ([fileManager contentsEqualAtPath:@"FilePath1" andPath:@" FilePath2"]) {
         NSLog(@"Same content");
 }

Check if writable, readable and executable

 
 if ([fileManager isWritableFileAtPath:@"FilePath"]) {
         NSLog(@"File isWritable");
 }

  if ([fileManager isReadableFileAtPath:@"FilePath"]) {
          NSLog(@"File isReadable");
 }


 if ( [fileManager isExecutableFileAtPath:@"FilePath"]){
          NSLog(@"File is Executable");
 }

Move file

 if([fileManager moveItemAtPath:@"FilePath1" toPath:@"FilePath2" error:NULL]){
          NSLog(@"File Moved successfully");
 }

Copy file

 
if ([fileManager copyItemAtPath:@"FilePath1" toPath:@"FilePath2" error:NULL]) {
          NSLog(@"File Copied successfully");
 }

Remove file

 if ([fileManager removeItemAtPath:@"FilePath" error:NULL]) {
          NSLog(@"File Removed successfully");
 }

Read file

 NSData *data = [fileManager contentsAtPath:@"Path"];

Write file

 [fileManager createFileAtPath:@"" contents:data attributes:nil];

Delegates in iOS – A Simple Example

Hi All,

Today I am going to talk about iOS Delagates.
This example shows how to write a common delegate for a mail composer in iOS.

First I am going to crate a seperate class for invoking the MailComposer Modal view controller.
The class is named “Common”.

So Create .m and .h files for Common.

Common.h

#import <Foundation/Foundation.h>
#import <MessageUI/MessageUI.h>

@interface Common : NSObject{
    
    MFMailComposeViewController *mailComposer;
    
}

@property (nonatomic, weak) id <MFMailComposeViewControllerDelegate> delegate;

-(void)sendMail:(UIViewController *) cont : (NSString *) mailSubject : (NSString *) mailBody;

-(void) setDelegate:(id <MFMailComposeViewControllerDelegate>)aDelegate;

@end

Now Go to Common.m and implement the methods.

#import "Common.h"

@implementation Common

@synthesize delegate;

-(void)sendMail:(UIViewController *) cont :(NSString *) mailSubject : (NSString *) mailBody{
    
    mailComposer = [[MFMailComposeViewController alloc]init];
    [mailComposer setSubject:mailSubject];
    mailComposer.mailComposeDelegate = delegate;
    [mailComposer setMessageBody:mailBody isHTML:NO];
    [cont presentViewController:mailComposer animated:YES completion:nil];
    
}

-(void) setDelegate:(id <MFMailComposeViewControllerDelegate>)aDelegate{
    if (delegate != aDelegate) {
        delegate = aDelegate;        
    }
}

@end

Now Go to ViewController.h

We don’t need any declarations inside this class, just need to add the delegate

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

@interface ViewController : UIViewController<MFMailComposeViewControllerDelegate>
{
    
}
@end

Now in the implementation class

ViewController.m

#import "ViewController.h"
#import "Common.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{

    Common *com = [Common new];
    [com setDelegate:self];   // Setting the Mail Composer delegate
    [com sendMail:self :@"Mail Subject" :@"Mail Body"];
    
}


#pragma mark - mail compose delegate
-(void)mailComposeController:(MFMailComposeViewController *)controller
         didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
    if (result) {
        NSLog(@"Result : %d",result);
    }
    if (error) {
        NSLog(@"Error : %@",error);
    }
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

Ok. Now our MailComposer Delegate is implemented. Go on and run the application.

Xcode 6 crashes when validating or submitting app archive.

Before somedays some people might have experienced this issue when you are trying to
validate or while submitting, the Xcode just crashes.

However its the problem with the XCode due to wrong programming practice or
not a professional approach from Apple. Apple could have warned the user about what is wrong.

There is a simple solution to this.

  • To check if you need to, you can go to the preferences -> accounts in XCode, Click “View details” of an account and
    attempt to refresh using the little button. Here, XCode will warn you that you need to accept new agreements in the
    Member Center before you can refresh.
  • if ther is any, then you have to go to the Member Center (https://developer.apple.com/devcenter/ios/index.action)
    and Accept all agreements.
  • Double click new provision profiles you downloaded to install them, and then XCode will never crash.

  • The problem is caused by XCode 6.0 does not handle provision profile migration properly.
    Developers should regenerate provision profiles for XCode 6+, but Xcode 6.0 fails to display this error message properly and crashes. (If you use XCode 6.1 Beta, it will display error messages for you, no crash.
    Then you will know that the problem is caused by “invalid”==”legacy” provision profile.)

    After that try again validating and submitting your app and it should Work successfully.

    Thanks for reading this post, if the above solution works, then please rate and comment below.

    How to add info button to right side or leftside of navigationbar in iPhone?

    
        UIButton* infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
        [infoButton addTarget:self action:@selector(showInfoView:) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:infoButton];
    
    

    Adding button action function.

    - (IBAction)showInfoView:(id)sender {
        
    }
    

    Random Integer array without repetition in Objective C Iphone

    This sample code generates a random number and checks whether its already present in the array.
    If yes then it will not add else it will add, thus generating a random array without duplicates.

    -(NSMutableArray *) generateRandomArray : (int) max{
        NSMutableArray *randArray = [NSMutableArray new];
        for (int k = 0; k < max; k++) {
           int r = arc4random() % max;
            if([randArray containsObject:[NSString stringWithFormat:@"%d", r]]){
                k--;
            }else{
                [randArray addObject:[NSString stringWithFormat:@"%d", r]];
            }
        }
        NSLog(@"RAND %@",randArray);
        return randArray;
    }
    

    Please leave your valuable comments if you found this post useful.

    How to split a string using a delimiter in iPhone and add it to a mutable array?

    Here is a simple code that does this..

    -(NSMutableArray *) getAnswers :(NSString *) yourstring{
        NSMutableArray *answers = [NSMutableArray new];
        NSArray *parts = [[yourstring componentsSeparatedByString:@","];
        for(NSString *str in parts){
            [answers addObject:str];
        }
        NSLog(@"RET answers %@", answers);
        return answers;
    }
    

    After splitting the string with “componentsSeparatedByString” the parts are added to a NSMutableArray using addObject.

    A 4.8 inch iPhone may be on the way

    Every iPhone user may be envious on seeing a bigger screen Android Phone.

    iPhone 5S

    But don’t worry Apple is said to be working on an iPhone with a 4.8-inch screen, a 20% increase in screen size from the iPhone 5S, iPhone 5C and iPhone 5.

    Jeffries analyst Peter Misek has issued a research note to investors where he cited supply chain sources in China claiming that Apple will unveil an iPhone with 4.8-inch screen. This model is scheduled to be launched in September next year and will be named iPhone 6, said Misek.

    You can read more about the story from here

    Apple iPhones may come up with as less as $99 in the future

    iPhone

    Yes,
    these are the rumours about the future iphone. Apple is reportedly looking at iPhones with bigger screens and will be releasing the low cost phone in
    a range of colors as soon as this year, the ABC News reports.

    According to the report, Apple declined to comment on the rumors,
    Cook also said the iPhone doesn’t have a larger screen right now for a few reasons.

    He said that a large screen today comes with a lot of tradeoffs, adding that people do look at the size, but they also look at things like if the photos show the proper color, the white balance, reflectivity, battery life, brightness, the longevity of the display.

    Read more from here

    Google’s Android will beat Apple’s iphone in total number of apps downloaded in next few months.

    Google Android

    Analysts are saying that Google play store will be the most popular platform for downloading mobile apps in the next few months.

    History of Google Play
    Google Play, formerly known as the Android Market, is a digital application distribution platform for Android and an online electronics store developed and maintained by Google. The service allows users to browse and download music, magazines, books, movies, television programs, and applications published through Google. Users can also purchase Chromebooks and Google Nexus–branded mobile devices through Google Play.
    Applications are available either for free or at a cost. They can be downloaded directly to an Android or Google TV device through the Play Store mobile app, or by deploying the application to a device from the Google Play website. These applications are generally targeted to users based on a particular hardware attribute of their device, such as a motion sensor (for motion-dependent games) or a front-facing camera (for online video calling).

    You can read more about Google Play Store from here

    Budget iPhone 5 Coming Soon

    iPhone 5

    The budget version of Apple’s latest iPhone will cost roughly $330 (£220), priced in order to appeal to young, middle class consumers in countries like China and India.
    The claims about the price and the imminent release were made on the Japanese website Macotakara, following on from earlier reports about Apple plans for a cheaper phone.
    In January it was reported that the planned new phone will resemble the iPhone 5 from the front but Apple will replace that handset’s aluminium body with a cheaper plastic casing.

    Read More from here
    http://www.telegraph.co.uk/technology/apple/9902864/Budget-iPhone-5-to-launch-soon.html

    iPhone Mini launch this summer

    iPhone Mini

    A low-priced iPhone makes a lot of sense, Morgan Stanley says, and it even could hit the market this summer.
    Katy Huberty, an analyst with the banking firm, noted that after her meetings with Apple Chief Financial Officer Peter Oppenheimer, she’s convinced that innovation remains a top priority for the Cupertino, Calif., electronics giant. She also believes that Apple will increase cash return to shareholders and expand carriers, distribution, and possibly price points to drive iPhone growth.
    She noted that a lower priced iPhone makes sense for several reasons:
    “iPad Mini is expanding Apple’s customer base with 50 [percent] of purchases in China/Brazil representing new customers to the ecosystem.”
    “Chinese consumers show a desire to purchase the latest version of iPhone (instead of discounted older generations).”
    “iPhone 4 demand surprised to the upside in the December quarter.”

    Read more from here

    http://news.cnet.com/8301-13579_3-57570715-37/iphone-mini-launch-this-summer-makes-sense-analyst-says/

    How to Change UIWebview’s background color in iPhone Xcode?

    Unlike other UIViews, the UIWebview’s opaque property is set to true by default. That should be set to false for changing the background color.

    [myWebView setOpaque:NO];
    
    myWebView.backgroundColor=[UIColor redColor];
    

    Samsung Year in Review: Galaxy Triumphs, Apple Losses

    Samsung produces a number of products – from kitchen appliances to PCs – but it was the company’s mobile division that made the most headlines in 2012.
    The Korea-based company dominated the mobile phone space, introducing several new Galaxy devices throughout the year. But it couldn’t shake one its biggest rivals, Apple, which proved to be a worthy opponent in the courtroom and in stores.
    Still, despite all the hysteria surrounding the launch of the iPhone 5 and iPad mini, it was Samsung and its Android-heavy lineup of devices like the Galaxy S III and Galaxy Note II that were the really mobile winners in 2012. Those two smartphones were only introduced in the second half of the year and they have already sold at least 30 million and 5 million worldwide, respectively.

    Read more from here..

    http://www.pcmag.com/article2/0,2817,2413529,00.asp

    Apple fined by China court for copyright violation

    A court in China has ordered Apple to pay compensation to eight Chinese writers and two companies for violating their copyrights.

    They had claimed that unlicensed electronic versions of their books had been sold on Apple’s online store.

    The court ordered Apple to pay them 1.03m yuan ($165,000; £100,000) in compensation, according to the official news agency Xinhua.
    … Read more from here.

    http://www.bbc.co.uk/news/business-20856199

    How to find your Google Plus ID

    This is so simple

    1. Go to your Google + account (https://plus.google.com/).

    2. Click on the Profile icon on the Left.

    3. If you look at the URL in the address bar, it should look something like this:

    https://plus.google.com/104653270154306099169/posts

    4. The long numerical string in the URL is your Google+ ID. Here is CoderzHeaven’s from the URL above:

    104653270154306099169/

    Google + CoderzHeaven

    Apple again the most valuable brand.

    Apple took the top spot for the second year in a row, beating out IBM, Google, and McDonald’s to assume the position of the world’s most valuable brand.

    At $183 billion, Apple is the world’s most valuable brand, according to Millward Brown Optimor’s annual BrandZ study. Apple was last year’s most valuable brand, as well, though the company’s value jumped 19 percent over last year’s $153.3 billion tally.

    Read more from here..

    http://news.cnet.com/8301-1001_3-57439046-92/apple-again-the-worlds-most-valuable-brand-google-third/

    Apple late in China – Samsung already has almost triple share.

    Apple Inc. (AAPL) got a partner to sell the iPhone in the world’s biggest mobile-phone market, China. The may be too late to catch Samsung with a market share that’s three times larger and growing.
    Samsung controlled 24.3 percent of the market for phones in China.
    “I don’t expect Apple to replace Samsung any time soon,” Gartner analyst Sandy Shen said in an interview. “China Telecom is the nation’s smallest carrier, so the extent to which they can help Apple is quite limited.”

    Read more about this story from here.
    http://www.bloomberg.com/news/2012-03-11/iphone-fails-to-gain-china-share-as-samsung-lead-triples-tech.html