Simple way to implement multi-thread

I want show you simple way to create multi-thread calculations in few strings of code.

Simple collection of operations. But remember about blocks specifications and use proper storage type.

1
2
3
4
5
6
7
NSMutableArray *operations = [NSMutableArray array];
    for (...) {
        NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
           // calculation
        }];
        [operations addObject:operation];
    }

If you don’t like blocks, you can easily make a subclass of NSOperation and overwrite main function.

Now time to create queue for operations, so just create instance of NSOperationQueue.
And in maxConcurrentOperationCount property you need setup proper value. For example 2, if you want to use just 2 concurrent threads for your calculations and continue in normal state with others operations in another threads.
In this case waitUntilFinished should be NO.

But if you want to use max threads of CPU, setup NSOperationQueueDefaultMaxConcurrentOperationCount to maxConcurrentOperationCount and YES to waitUntilFinished. Like in example below:

1
2
3
4
5
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue setMaxConcurrentOperationCount:....];
    [queue addOperations:operations waitUntilFinished:YES];
    [queue waitUntilAllOperationsAreFinished];
    [operations removeAllObjects];

If this is set, it will choose an appropriate value based on the number of available processors and other relevant factors.

1
2
3
enum {
  NSOperationQueueDefaultMaxConcurrentOperationCount = -1
};

NSOperationQueueDefaultMaxConcurrentOperationCount: The default maximum number of operations is determined dynamically by the NSOperationQueue object based on current system conditions.

That it! It’s so simple today.

How to add Push Notifications to your iOS application

Hi guys!

Welcome to 5 Min Guide about how to integrate Push Notifications into your application.

Push notification allows App to notify you of new messages or events without need to open the application in fact, they are similar to usual text message which appears like a popup on your screen with a sound.

This is a great way for apps to interact with us in the background, whether it is a game that notifies us of some event occurring in our game world or simple mail application that is beeping when a new message appears in our inbox.

As you know, Push Notifications require server side (3rd party server), e.g. for storing device tokens and for sending push notifications:

Some people still have problems with this – they  think that they should develop this server by themself, lots of hard work, time, money, etc.

But stop! We live in the mobile era! All this hard work is already done by another people. All you need – just use ready made products.  Do not reinvent the wheel!

And, one such product is QuickBlox. QuickBlox is a cloud hosted platform to simplify your mobile app backend development. It has lots of Great Features for any platform such Push Notifications, Location, Content, Ratings features, Social integration, Chat and lots of other mobile killer features!

Today we are going to talk about how to integrate one of these great feature to your iOS mobile application – Push Notifications, provided by QuickBlox Messages module. So, let’s start!

Continue reading

Subclass of UITextView with syntax highlighting for iOS 5.0 not finished (just sample)

With new iOS 6.0 everyone junior iOS developer can do code editor application with syntax highlighting. Because UITextView has attribute attributedText, which has enough parameters and functionality for it.

So, I want to say, my old project does not have sense. :)

The last build shared on git hub and everyone can modify it and try to finish, because it still not completed. Still has a problem with word wrap.

Maybe someone will get something new for self. Because this project used CoreText and CoreGraphics framework.

Enjoy!

Posted in Apple, iOS, iPad, iPhone, OOP
Tagged CoreGraphics, CoreText, framework, github.com, highlighting, iOS 5.0, syntax, UITextView


Project based on DETweetComposeViewController

Facebook connection with Facebook SDK 3.0.x (last at 2 september 2012)

What is it?
DEFacebookComposeViewController is an iOS 4 compatible composer view for posting picture and message on user wall.
Looks like the Facebook Sheet in iOS 6.

How to use:
1. download and setup Facebook sdk

2. register your app on

3. replace appID in plist file. FacebookAppID and in CFBundleURLTypes

4. #import “DEFacebookComposeViewController.h”

5. use this code for posting

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 DEFacebookComposeViewControllerCompletionHandler completionHandler = ^(DEFacebookComposeViewControllerResult result) {
        switch (result) {
            case DEFacebookComposeViewControllerResultCancelled:
                NSLog(@"Facebook Result: Cancelled");
                break;
            case DEFacebookComposeViewControllerResultDone:
                NSLog(@"Facebook Result: Sent");
                break;
        }
       
        [self dismissModalViewControllerAnimated:YES];
    };
   
    DEFacebookComposeViewController *facebookViewComposer = [[DEFacebookComposeViewController alloc] init];
    self.modalPresentationStyle = UIModalPresentationCurrentContext;
    [facebookViewComposer setInitialText:@"Look on this"];
    [facebookViewComposer addImage:[UIImage imageNamed:@"1.jpg"]];
    facebookViewComposer.completionHandler = completionHandler;
    [self presentViewController:facebookViewComposer animated:YES completion:^{ }];

Posted in iOS, iPad, iPhone
Tagged DETweetComposeViewController, Facebook, iOS 4, iOS 6, MVC, , SDK

Custom UINavigationBar

Create image for navigation background – portrait
UIImage *NavigationPortraitBackground = [[UIImage imageNamed: @"navigationbarPortrait.png"]
resizableImageWithCapInsets: UIEdgeInsetsMake(0, 0, 0, 0)];

Create image for navigation background – landscape
UIImage *NavigationLandscapeBackground = [[UIImage imageNamed: @"navigationbarLandscape.png"]
resizableImageWithCapInsets: UIEdgeInsetsMake(0, 0, 0, 0)];

Set the background image all UINavigationBars
[[UINavigationBar appearance] setBackgroundImage: NavigationPortraitBackground
forBarMetrics: UIBarMetricsDefault];
[[UINavigationBar appearance] setBackgroundImage: NavigationLandscapeBackground
forBarMetrics: UIBarMetricsLandscapePhone];

Set attributes for buttons and title
NSMutableDictionary *attributes = [NSMutableDictionary dictionary];

[attributes setValue: [UIColor colorWithRed: 0.96f green:0.91f blue:0.64f alpha:1.00f] forKey: UITextAttributeTextColor];
[attributes setValue: [UIColor clearColor] forKey: UITextAttributeTextShadowColor];
[attributes setValue: [NSValue valueWithUIOffset: UIOffsetMake(0.0, 0.0)] forKey: UITextAttributeTextShadowOffset];
[[UIBarButtonItem appearance] setTitleTextAttributes: attributes forState: UIControlStateNormal];

[[UINavigationBar appearance] setTitleTextAttributes: attributes];

Easy custom back button

1
2
3
4
UIButton* customBackButton = [UIButton buttonWithType:101];
    [customBackButton setTitle:@"Back" forState:UIControlStateNormal];
    [customBackButton setCenter:self.view.center];
    [self.view addSubview:customBackButton];

Create movie from array of images

Create movie from images seq.

First part of method, initialize

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
- (void) writeImagesAsMovie:(NSArray *)array toPath:(NSString*)path {
   
NSString *documents = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex: 0];
    documents = [documents stringByAppendingPathComponent:currentWorkspace];
   
    //NSLog(path);
    NSString *filename = [documents stringByAppendingPathComponent:[array objectAtIndex:0]];
    UIImage *first = [UIImage imageWithContentsOfFile:filename];
   
   
    CGSize frameSize = first.size;
   
    NSError *error = nil;
    AVAssetWriter *videoWriter = [[AVAssetWriter alloc] initWithURL:
                                  [NSURL fileURLWithPath:path] fileType:AVFileTypeQuickTimeMovie
                                                              error:&error];
   
    if(error) {
        NSLog(@"error creating AssetWriter: %@",[error description]);
    }
    NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                   AVVideoCodecH264, AVVideoCodecKey,
                                   [NSNumber numberWithInt:frameSize.width], AVVideoWidthKey,
                                   [NSNumber numberWithInt:frameSize.height], AVVideoHeightKey,
                                   nil];
   
   
   
    AVAssetWriterInput* writerInput = [[AVAssetWriterInput
                                        assetWriterInputWithMediaType:AVMediaTypeVideo
                                        outputSettings:videoSettings] retain];
   
    NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];
    [attributes setObject:[NSNumber numberWithUnsignedInt:kCVPixelFormatType_32ARGB] forKey:(NSString*)kCVPixelBufferPixelFormatTypeKey];
    [attributes setObject:[NSNumber numberWithUnsignedInt:frameSize.width] forKey:(NSString*)kCVPixelBufferWidthKey];
    [attributes setObject:[NSNumber numberWithUnsignedInt:frameSize.height] forKey:(NSString*)kCVPixelBufferHeightKey];
   
    AVAssetWriterInputPixelBufferAdaptor *adaptor = [AVAssetWriterInputPixelBufferAdaptor
                                                     assetWriterInputPixelBufferAdaptorWithAssetWriterInput:writerInput
                                                     sourcePixelBufferAttributes:attributes];
   
    [videoWriter addInput:writerInput];
   
    // fixes all errors
    writerInput.expectsMediaDataInRealTime = YES;
   
    //Start a session:
    BOOL start = [videoWriter startWriting];
    NSLog(@"Session started? %d", start);
    [videoWriter startSessionAtSourceTime:kCMTimeZero];

Continue reading

ScrollView with scroll’s indicators, which are shown all the time.

UPDATE: This solution could cause some issues on iOS 7. For more detail look .

My simple solution by writing category for UIImageView, because scroller is imageview.

How to use :)
Just setup tag for your scrollview and you will get one with scroll indicators, which are shown all the time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#define noDisableVerticalScrollTag 836913
#define noDisableHorizontalScrollTag 836914

@implementation UIImageView (ForScrollView)

- (void) setAlpha:(float)alpha {
   
    if (self.superview.tag == noDisableVerticalScrollTag) {
        if (alpha == 0 && self.autoresizingMask == UIViewAutoresizingFlexibleLeftMargin) {
            if (self.frame.size.width < 10 && self.frame.size.height > self.frame.size.width) {
                UIScrollView *sc = (UIScrollView*)self.superview;
                if (sc.frame.size.height < sc.contentSize.height) {
                    return;
                }
            }
        }
    }
   
    if (self.superview.tag == noDisableHorizontalScrollTag) {
        if (alpha == 0 && self.autoresizingMask == UIViewAutoresizingFlexibleTopMargin) {
            if (self.frame.size.height < 10 && self.frame.size.height < self.frame.size.width) {
                UIScrollView *sc = (UIScrollView*)self.superview;
                if (sc.frame.size.width < sc.contentSize.width) {
                    return;
                }
            }
        }
    }
   
    [super setAlpha:alpha];
}
@end

If you want both scroll it’s easy to change code.

1 2 3 4