Showing posts with label iOS. Show all posts
Showing posts with label iOS. Show all posts

Monday, July 24, 2017

Compress File(s) with using Minizip and ZipArchive – iPhone / iPad

Here's a simple class for compressing and extracting files. Its work depends on minizip, which is a open source zip format library.

The major class name is ZipArchive, it’s easy to use, you can declare a instance and call initialize functions, and then call addFileToZip or UnzipFileTo to finish compression or uncompression. Lets see how to use it.

------------------------------
First download ZipArchive and Minizip from here.

Add all the files to you project, and and framework libz.1.2.3.dylib

Include ZipArchive.h using #import "ZipArchive/ZipArchive.h" or #import "ZipArchive.h"

------------------------------

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

//get app’s documents directory

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *tmpPathToFile = [documentsDirectory stringByAppendingPathComponent:@"mypicture.jpg"];

//you can give any name to zip file and ZipArchive will save the zip file to your app’s document directory.

NSString *zipFileTo = [documentsDirectory stringByAppendingPathComponent:@"mycompressedfile.zip"];

ZipArchive *zip = [[ZipArchive alloc] init];

BOOL result = [zip CreateZipFile2:zipFileTo];

//add only one file

ret = [zip addFileToZip:tmpPathToFile newname:@"mypicture.png"];

//add multiple files to your zip file. sample “files” array is an NSMutableArray and it contains only file name like, “mypicture1″, “mypicture2″

for (int i = 0; i<[files count]; i++) {

//physical path of your file

NSString *otherFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",[files objectAtIndex:i]]];

//add the file with new name

ret = [zip addFileToZip:otherFiles newname:[NSString stringWithFormat:@"%@.png",[files objectAtIndex:i]]];

}

BOOL success = [zip CloseZipFile2];

[zip release];

Tuesday, June 11, 2013

Apple’s WWDC 2013 Keynote: Highlights

So there you have it, the announcement of this year’s Apple Worldwide Developers Conference (WWDC) 2013. This year, Apple gave fair warning for ticket sales and the public responded by giving giving Apple it’s fastest sold out event ever: 71 seconds. Attendees came in from 66 countries and two-thirds of them are first-time attendees.

Everyone got something from the latest WWDC keynote address. We got a new, cylinder(!) Mac Pro (tell us if you love or hate the new design), and a new OS – OS X Mavericks (they ran out of cats), with higher responsiveness and longer battery life (it’s about time); Maps gets a second chance, users get a new password-management system for iCloud, Finder gets an update and more.
If you missed it, here is a quick recap of the highlights.

1. OS X Mavericks

So because of a dwindling supply of cats, the 10th OS version was named OS X Sea Lion , OS X Mavericks, and it promises to extend battery life and provide better responsiveness, hitting a 1.4x performance improvement over Mountain Lion.

App Nap

App Nap selectively assigns power to the thing that has your immediate attention and runs on OpenGL 4 for super-responsive graphics.

Timer Coalescing

Timer Coalescing lets the CPU power up from idle mode on lower energy needs, reducing CPU memory by 72%. Even Safari has a Power Saver option to help direct power to what is in the centre of your attention.
With shared memory resource cache and power saver, Safari kills the competition, and is said to be run on only one-third of the energy of Firefox.


Apart from being able to share links more easily via Linkedin and Twitter, Safari now sports a sidebar bookmark, which actually lets you go through your Reading List as you read.

Finder Tabs

Your Finder is going the way of Tabs, like how it is with major browsers these days. Rather than have so many windows, just open up all your files into multiple tabs.
Open windows can be merged into tabs with just one clicks and files can be transferred from one folder to another just by hovering over the tabs.

Tagging

Tagging is brought to the Mac. Save a document and give it a tag and have the tags turn up automatically on the sidebar. As tagging can now be done anywhere, including on files on the iCloud, all files with the same tags can be pulled up with a single click.
Users can assign multiple tags to the same document, making all their files easy to search and retrieve.

Multiple Display

Multiple Display support allow you to work on, multiple screens, even though only one device is physically connected, even if it means you are using Apple TV as one of your screens. Full screen spaces can be pulled from one display to the next and the dock and other menus will be displayed on each connected screen as well.

Password Management With KeyChain

Apple is taking it upon themselves to better safeguard and help their users better remember their passwords, account information, Wifi-networks and even credit card numbers with iCloud KeyChain. Safari auto-suggests passwords for you, and even extends this option to your logged-in credit card information.

Respond Via Notifications

They hit the jackpot this time with responsive notifications, allowing you to reply to notifications on your Mac, as if you were on the iPhone.
Reply straight to friends who are messaging you over messaging apps, delete emails as they come in (straight on the notification), reply Facetime calls with a text message (although I’m driving now doesn’t work) among others. All notifications are logged in, and will pop up when your machine wakes from sleep.

Smarter Calendar

You can now integrate your calendar with your Facebook calendar, but more importantly, setting up an event like a simple Lunch date, prompts the calendar to suggest places for you to dine in, gives you projected weather forecasts as well as suggestions on travel time (and when you should make a move).


Sounds like Google Now to me but hey, this one lets you send your information to our iPhone when you’ve got to go, so that’s a plus.

Smoother Maps

Apart from sending calendar events and suggestions to your iPhone, you can also send directions on the Map app to the iPhone from your Mac. This will show on your lockscreen and once you are in your phone, you are taken straight to navigation.
The Map app looks smoother and 3D rendering of the Flyover data looks stunning. Just give it a spin and rotate around the Eiffel Tower to have a look.

iBooks on Your Mac

iBooks is now available on the Mac, giving users access to 1.8 million books including interactive textbooks. The table of contents can be found at the bottom of the book title, and finding a page is as easy as scrolling through the pages at bottom of the book.
You can add notes in between, highlight important text and generate study cards from those marked passages for a highly interactive learning experience.

Macbook Air Lasts ‘Full Day’

I’ll keep it brief. Enhanced battery life. 4th generation Intel core processor. Haswell ULT. 40% faster graphics, dual GPU execution units. With all this, your Air can wake up in a second, or stay on standby for 30 days.
The 11” also got an extension in battery life, staying awake now for to 9 hours. 13” goes from 7 hour battery life to 12 hours. Good news for power users on the go. 11′ starts at $999 with 128GB; 13′ starts at $1099. Both start shipping today.


Mac Pro (Became a cylinder)

When, they innovate, they innovate. The new Mac Pro now only takes up one-eighth of the original volume and packs a power in its relatively tiny frame. Two times faster than the old Mac Pro, this new addition to the family has a ‘central thermal core’ running on 12-core Intel Xeon processor, Flash storage, supports 4K displays and is available only at the end of the year.
Prices yet to be announced. And oh yeah, you can hardly recognize it too.


iOS 7

Oh yes, we got a new mobile OS version and iOS 7 promises new features (Control Center, Airdrop for iOS, smarter multitasking etc) that you shouldn’t miss and new designs as well. Siri gets a new look, we’re getting iTunes Radio, and iOS comes to life in your vehicle.
I've devoted another post to just the enhancements done to iOS 7 just so you can get to the nitty-gritty details. So don’t miss out on that.

Saturday, June 1, 2013

Using EventKit in iOS

What's EventKit?

It is a framework provided by Apple in iOS 4+ for integrating your iOS app with the built in calendar app (iCal). You are able to retrieve events from the calendar, as well as create, update and delete events.

The Simulator

Although there is no calendar application in the iOS simulator, you can still use it for EventKit development using some open source code such as this.

Fetching Events

Retrieving stored events from a users calendar is super simple. The only parameters you need to specify is a date range and the calendar you want to query.

EKEventStore *eventStore = [[EKEventStore alloc] init];

NSDate *startDate = [NSDate date];
NSDate *endDate   = [NSDate distantFuture];

NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:startDate
                                                             endDate:endDate
                                                           calendars:nil];
                                                           
NSArray *events = [eventStore eventsMatchingPredicate:predicate];

Calendars within the Calendar app

The calendar app is made up of many calendars, e.g. Home calendar, Work calendar, Birthday calendar etc. Every event created must belong to a calendar, however some calendars are read-only.
You can retrieve the following calendar information in iOS 4:

EKEventStore *eventStore = [[EKEventStore alloc] init];

// Get all calendars
NSArray * calendars = [eventStore calendars];

// Get the default calendar
EKCalendar * calendar = [eventStore defaultCalendarForNewEvents];

// Test if calendar is read-­‐only
[calendar allowsContentModifications];

// Get the associated colour of a calendar
[UIColor colorWithCGColor:calendar.CGColor];

Inserting Events

As the following code illustrates, inserting an event to a users calendar is also fairly simple.

EKEventStore *eventStore = [[EKEventStore alloc] init];

EKEvent *event  = [EKEvent eventWithEventStore:eventStore];
event.calendar  = [eventStore defaultCalendarForNewEvents];
event.title     = @"WWDC";
event.location  = @"San Francisco";
event.notes     = @"Apple Developer Conference";
event.startDate = startDate;
event.endDate   = endDate;
event.allDay    = YES;

[eventStore saveEvent:event span:EKSpanThisEvent error:nil];

Inserting Events with EventKitUI

Instead of saving the created event directly into the event store, a better approach is to use EventKitUI which will allow the user visually check/modify an event before it is inserted.

EKEventStore * eventStore = [[EKEventStore alloc] init];

EKEvent * event = [EKEvent eventWithEventStore:eventStore];
event.title     = title;
event.location  = location;
event.startDate = startDate;
event.endDate   = endDate;
event.notes     = notes;

EKEventEditViewController *controller = [[EKEventEditViewController alloc] init];

controller.eventStore       = eventStore;
controller.event            = event;
controller.editViewDelegate = self;

[self presentViewController:controller animated:YES completion:nil];


If you use EventKitUI, remember to always set the editViewDelegate delegate, and implement a delegate method to handle the dismissal of the view controller window.

-(void)eventEditViewController:(EKEventEditViewController *)controller
         didCompleteWithAction:(EKEventEditViewAction)action {
    
    switch (action) {
       case EKEventEditViewActionCanceled:
           // User tapped "cancel"
           break;
       case EKEventEditViewActionSaved:
           // User tapped "save"
           break;
       case EKEventEditViewActionDeleted:
           // User tapped "delete"
           break;
       default:
           break;
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

Resources

Saturday, May 25, 2013

Custom Push in/out Transition Animation for Modal View Controllers

Implementing a custom transition animation for view controllers is not too difficult. Let's consider that we need to push from right/left when presenting a modal view controller, and then pushing out to the other direction when dismissing the dialog. The below mentioned UIViewController category serves this purpose for us.

@interface UIViewController (Transitions)

- (void) presentModalViewController:(UIViewController *)modalViewController withPushDirection: (NSString *) direction;
- (void) dismissModalViewControllerWithPushDirection:(NSString *) direction;

@end  

and the implementation:

#import "UIViewController+Transitions.h"

@implementation UIViewController (Transitions)

- (void) presentModalViewController:(UIViewController *)modalViewController withPushDirection: (NSString *) direction {
    
    [CATransaction begin];
    
    CATransition *transition = [CATransition animation];
    transition.type = kCATransitionPush;
    transition.subtype = direction;
    transition.duration = 0.25f;
    transition.fillMode = kCAFillModeForwards;
    transition.removedOnCompletion = YES;
    
    [[UIApplication sharedApplication].keyWindow.layer addAnimation:transition forKey:@"transition"];
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    [CATransaction setCompletionBlock: ^ {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(transition.duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^ {
            [[UIApplication sharedApplication] endIgnoringInteractionEvents];
        });
    }];
    
    [self presentViewController:modalViewController animated:NO completion:nil];
    
    [CATransaction commit];
    
}

- (void) dismissModalViewControllerWithPushDirection:(NSString *) direction {
    
    [CATransaction begin];
    
    CATransition *transition = [CATransition animation];
    transition.type = kCATransitionPush;
    transition.subtype = direction;
    transition.duration = 0.25f;
    transition.fillMode = kCAFillModeForwards;
    transition.removedOnCompletion = YES;
    
    [[UIApplication sharedApplication].keyWindow.layer addAnimation:transition forKey:@"transition"];
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    [CATransaction setCompletionBlock: ^ {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(transition.duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^ {
            [[UIApplication sharedApplication] endIgnoringInteractionEvents];
        });
    }];
    
    [self dismissViewControllerAnimated:NO completion:nil];
    
    [CATransaction commit];
    
}

@end

To use it, you import "UIViewController+Transitions.h" in your file and call the presentModalViewController:withPushDirection:
the direction parameter receives core animation transition sub-types such as kCATransitionFromRight.
You can download the category files from here and import to your project.

Enjoy...

Saturday, January 5, 2013

Listing the Fonts Available in iOS


iOS 5.0 was a huge update in many ways and one of them is built-in font selection. For the first time ever, iPhone and iPad have exactly the same fonts! Many times, we need to know the list of available fonts in iOS, sometimes to display to end-user so that he can write any text in custom font or sometimes to know ourselves the available fonts which we can use. Since Apple is always adding to the available fonts with each iOS release, the best way to know what fonts you can use is to query the iOS for available fonts under the UIFont class.Here is an excellent bit of compact code to print out the available fonts to your console.

NSMutableArray *fontNames = [[NSMutableArray alloc] init];
NSArray *fontFamilyNames = [UIFont familyNames];
for (NSString *familyName in fontFamilyNames) {
    NSLog(@"Font Family Name = %@", familyName);
    NSArray *names = [UIFont fontNamesForFamilyName:familyName];
    NSLog(@"Font Names = %@", fontNames);
    [fontNames addObjectsFromArray:names];
}

Fonts are part of a font family, and the UIFont class returns a list of all of the font families available in iOS as well as the fonts under each font family. The code above first gets a list of all the font families, and then a list of all the fonts under each family, printing those font names out to the console.

Wednesday, May 30, 2012

iOS Paint tool using UIBezierPath


I was going through how to use UIBezierPath and what are its possible uses.. and I must say it is one hell of a convenient tool! Ofcourse you can draw normal drawing with it as shown below and use your app as sketching pad in addition to that it adds so much convenience with the undo and redo action that I fell in love with the use of UIBezierPath. You can have simple drawing as well as pattern based brush tip. It is so easy to use this as pencil tool that I don't even have words !

You can initialize the UIBezierPath as following
UIBezierPath *myPath = [[UIBezierPath alloc] init];
myPath.lineWidth = 10;
brushPattern = [UIColor redColor]; // This is the color of my stroke
Then you have Touch methods which handle and track the coordinates of your touch. When your touch begins on the screen, you ask UIBezierPath to move to that touch point.
UITouch *myTouch = [[touches allObject] objectAtIndex:0];
[myPath moveToPoint:[myTouch locationInView:self]; 
As you move your finger around, you keep adding those points in your BezierPath in TouchMoved method by following
UITouch * mytouch = [[touches allObjects] objectAtIndex:0];
[myPath addLineToPoint:[mytouch locationInView:self]];
As we need constant refreshing of the screen, so that as soon as we draw it appears on the screen, we refresh the UIView subclass by calling following method in TouchMethod so that as soon as there any change in the BezierPath, it is reflected on the screen.
[self setNeedsDisplay];
Talking about drawRect Method which does all the drawing for you, you need to set the color of your stroke (stroke color means the color with which painting will be done on screen) on screen and also the blend mode. You can try different blend mode and see the result.
[brushPattern setStroke];
[_path strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];




Pattern Brush.. it just changes the custom pattern color of the paint brush and allows you to use a custom image-pattern to be used instead of any specific color (which was red in our case)

myPath.lineWidth = 10; //This can help you in setting width of the stroke/brush
brushPattern = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"pattern.jpg"]]; // You can set pattern in your color of your brush so that the stroke will appear with pattern of your image


Adding Undo/Redo feature

We don't have to do much after this step for adding the undo/redo feature in the existing code.
Add following lines to header (.h) file
{
  NSMutableArray *pathArray;
  NSMutableArray *bufferArray;
}
- (void)undoButtonClicked;
- (void)redoButtonClicked;

First, we declare two NSMutable arrays, one each for 'undo' and 'redo' steps. Then we declare two methods that gets called when we want to undo/redo.

Go to implementation file (.m) and lets start be looking into touch delegate methods:
 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    myPath = [[UIBezierPath alloc] init];
    myPath.lineWidth = 10;
    UITouch *mytouch = [[touches allObjects] objectAtIndex:0];
    [myPath moveToPoint:[mytouch locationInView:self]];
    [pathArray addObject:myPath]; 
}
Here, whenever a new touch is detected, we initialize a new UIBezierPath and add it to "pathArray" (for undo steps)
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *mytouch = [[touches allObjects] objectAtIndex:0];
    [myPath addLineToPoint:[mytouch locationInView:self];
    [self setNeedsDisplay];
}
Next, each time a movement is detected, then we call 'setNeedsDisplay' and redraws the view which in turn calls 'drawRect' method
- (void)drawRect:(CGRect)rect

{
    [brushPattern setStroke];
    for (UIBezierPath *_path in pathArray)
        [_path strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
}
Since, 'pathArray' contains all the UIBezierPaths, it loops through each of them and paints them on screen.
Below are the actions that gets called upon when we click on undo/redo buttons:
- (void)undoButtonClicked {
   if([pathArray count]>0))
   {
        UIBezierPath *_path = [pathArray lastObject];
        [bufferArray addObject:_path];
        [pathArray removeLastObject];
        [self setNeedsDisplay];
    }
}

- (void)redoButtonClicked{
    if([bufferArray count]>0)) {
        UIBezierPath *_path = [bufferArray lastObject];
        [pathArray addObject:_path];
        [bufferArray removeLastObject];
        [self setNeedsDisplay];
    }
}

When undo button is clicked, we remove the last object from pathArray and save that object to 'bufferArray' - which stores all UIBezierPath for redo.
And when redo gets clicked, we remove the last object form 'bufferArray' and adds it to the 'pathArray'.
We ask the view to redraw itself again after performing any one of the above stuff.

That's all. This short code snippet lets you perform touch sensitive paint on iOS devices with properly working undo/redo functionality.

The complete code of above tutorial can be found on github.