UIAlertView with UITextField

I wanted to show an alertView to a user with a textField. This is what was achieved:

First, I tried to use Block Alerts and ActionSheets, but I failed. Then I discovered, that there is a standart way to do this. There are some UIAlertView styles available beyond a default style: UIAlertViewStyleLoginAndPasswordInput, UIAlertViewStylePlainTextInput and UIAlertViewStyleSecureTextInput. In this case we will use the second one. Works on iOS 5 and later:

UIAlertView *av = [[UIAlertView alloc] initWithTitle:LS(@"Document file name") message:@"Please enter document file name." delegate:self cancelButtonTitle:LS(@"Cancel") otherButtonTitles:LS(@"Save"), nil];
av.alertViewStyle = UIAlertViewStylePlainTextInput;
[av textFieldAtIndex:0].delegate = self;
[av textFieldAtIndex:0].text = self.mcAttachDisplayed.fileName;
[av show];

Then, you should define two protocols UITextFieldDelegate, UIAlertViewDelegate.
And implement methods:

- (BOOL)textFieldShouldReturn:(UITextField *)textField
    [textField resignFirstResponder];
    return YES;
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
    NSLog(@"Button index clicked:%d", buttonIndex);
    switch (buttonIndex) {
        case 0:
        case 1:{
            NSLog(@"Save Clicked");
            UITextField *textField = [alertView textFieldAtIndex:0];
            NSString *text = textField.text;

StackOverFlow question

How to Work With Flags in MailCore

Recently I was guessing, how to work with flags in MailCore, where a flag is NSUInteger. I got answer from MailCore Librelist.

The flags are stored as bitwise operations. If you want to check to see if a message is deleted, for example, you can do the following bitwise operation:

More explanation from me.

This is a list of Flags:

Meaning of the right column here is:

Let’s use a Decimal to Binary converter.

For instance, 34 is 100010. We see, that 2nd and 6th bits are not null. So Flags are CTFlagSeen and CTFlagForwarded. Since CTFlagSeen = MAIL_FLAG_SEEN = 1 << 1 in binary. It means, that we should shift by 1 symbol and compare 2nd symbol in 100010. It is 1, or YES. The same is for CTFlagForwarded which is a shift by 6. If flags = 50, then binary is 110010. Flags are CTFlagSeen, CTFlagAnswered, CTFlagForwarded. Let's now assume, that we want to remove CTFlagSeen flag. What should we do? If we do this: flags = flags^CTFlagSeen we will get this in bit level: (110010)^(1<<1)=(110000), so the flag will be removed. If there was no flag, it will be installed, when we use XOR operator, represented by ^ symbol. If 18, then 10010. Flags are CTFlagSeen (10) and CTFlagAnswered(101).

How To Change Back Button Title Of Navigation Bar On iOS

The key moment here is that you should change backBarButtonItem before pushing your view controller, where you expect to change back button title. Change only the title of item doesn’t work, the whole button should be replaced.

UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:LS(@"All") style:UIBarButtonItemStyleBordered target:nil action:nil];
    self.navigationItem.backBarButtonItem = backButton;
    [self.navigationController pushViewController:messageViewController animated:YES];

Case Insensitive Method to Find a String in Another String in iOS

Can be used to filter data under search bar. Personally I have developed it for this purpose.

Case Insensitive Method to Find a String in Another String in iOS:

- (BOOL)findString:(NSString*)searchString inString:(NSString*)bigString
    if ([bigString length]==0) {
        return NO;
    if (!([bigString rangeOfString:searchString options:NSCaseInsensitiveSearch].location == NSNotFound)) {
        return YES;
    return NO;

UISearchBar and UISearchDisplayController with Custom Cells Programmatically

This post is not a full tutorial of how to implement this. It is just my experience description. Probably, you have the same problem with custom cells, as I had. There are a lot of tutorials, search them in Google. Another nice tutorial.

I had highly customized cells, but couldn’t understand, why do they mess up, when search starts and self.searchDisplayController.searchResultsTableView is displayed with regular cell, but not customized cells. I tried to find solution for about 2-3 hours, then I decided to make exactly the same, as others did for using custom cells. I solved the problem, that was in the absence of two delegate properties in my code. This is the correct version, of how you should initialize your UISearchBar and UISearchDisplayController (if you are doing it programmatically).

Code for ViewDidLoad method:

The other parts are pretty analogous to the usual search bar usage with regular cells. For instance, look at Apple’s source code on this topic.

What is interesting, this works fine on iPad too even thought the frame is 320 px here.

UISearchBar Class reference

UISearchDisplayController Class Reference

How to Change String Encoding from KOI8-R to UTF8 in Objective-C

KOI8-R is an 8-bit character encoding, designed to cover Russian, which uses the Cyrillic alphabet. I was getting a fileName from IMAP in this encoding and wanted to convert it to normal readable UTF-8.

My question concerning this issue in stackoverflow was banned. I had to solve this myself and spent quite a bit of time.

There is one solution, that works for many encodings – to use CFString methods:

- (NSString*)decodeKOI8R:(NSString*)stringToDecode {
    CFStringRef aCFString = CFStringCreateWithCString(NULL, [stringToDecode UTF8String], kCFStringEncodingKOI8_R);
    NSString *decodedString = (__bridge NSString*)aCFString;
    return decodedString;

But for some reason it worked for UTF-7 but didn’t for KOI8-R.

I searched Google for hours, but couldn’t find a solution. Suddenly, I found a solution in MailCore CTBareAttachment class method, called decodedFilename.

This is ObjC code of that method:

-(NSString*)decodedName {
    return MailCoreDecodeMIMEPhrase((char *)[self.name UTF8String]);

This is a C language method, that converts char* to the NSString with a proper encoding.

NSString *MailCoreDecodeMIMEPhrase(char *data) {
    int err;
    size_t currToken = 0;
    char *decodedSubject;
    NSString *result;
    if (*data != '\0') {
        err = mailmime_encoded_phrase_parse(DEST_CHARSET, data, strlen(data),
                                            &currToken, DEST_CHARSET, &decodedSubject);
        if (err != MAILIMF_NO_ERROR) {
            if (decodedSubject == NULL)
            return nil;
    } else {
        return @"";
    result = [NSString stringWithCString:decodedSubject encoding:NSUTF8StringEncoding];
    return result;


#define DEST_CHARSET "UTF-8"

and mailmime_encoded_phrase_parse is a pretty complex method, that is not easy even to copy paste here. So, this problem seems to have no easy solution, except using this C method. Actually this method parses a phrase and calls decoding C method for each word. And I ended up using it.

iPhone 5: Что нового

Показали iPhone 5. Многие слухи оправдались. Что нового по сравнению с 4S:
1. Он стал тоньше и легче на 20%.
2. Процессор A6, который мощнее A5/A5X в 2 раза.
3. Экран длиннее: 640х1136 вместо старых 640×960. Диагональ больше на пол дюйма. Цвета насыщеннее на 44%.
4. Почти та же оптика, но качество фото выше. Панорамная съемка.
5. Меньше коннектор.
6. Поддержка LTE сетей.
7. iOS 6. Но она будет доступна на всех iPhone начиная с 3GS и на iPad2/New.
8. Задняя крышка из металла, а не стекла.

Подробнее тут

Simplest way to check for an active Internet Connection on iOS

Sometimes we need to check synchronously, if there is an internet connection. For instance, when an app totally depends on internet connection. This is the simplest way to check internet connection on iOS app synchronously without using Reachability class:

Taken from here.

Instead of Google it is better to use another lightweight website. But I use google.com, since it is always online and reliable and not very heavy page.