Category: iOS

  • 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:

    <br />
    – (NSString*)decodeKOI8R:(NSString*)stringToDecode {</p>
    <p>    CFStringRef aCFString = CFStringCreateWithCString(NULL, [stringToDecode UTF8String], kCFStringEncodingKOI8_R);<br />
        NSString *decodedString = (__bridge NSString*)aCFString;</p>
    <p>    return decodedString;<br />
    }<br />
    

    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:

    <br />
    -(NSString*)decodedName {<br />
        return MailCoreDecodeMIMEPhrase((char *)[self.name UTF8String]);<br />
    }<br />
    

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

    <br />
    NSString *MailCoreDecodeMIMEPhrase(char *data) {<br />
        int err;<br />
        size_t currToken = 0;<br />
        char *decodedSubject;<br />
        NSString *result;</p>
    <p>    if (*data != ‘\0’) {<br />
            err = mailmime_encoded_phrase_parse(DEST_CHARSET, data, strlen(data),<br />
                                                &currToken, DEST_CHARSET, &decodedSubject);</p>
    <p>        if (err != MAILIMF_NO_ERROR) {<br />
                if (decodedSubject == NULL)<br />
                    free(decodedSubject);<br />
                return nil;<br />
            }<br />
        } else {<br />
            return @””;<br />
        }</p>
    <p>    result = [NSString stringWithCString:decodedSubject encoding:NSUTF8StringEncoding];<br />
        free(decodedSubject);<br />
        return result;<br />
    }<br />
    

    Here

    <br />
    #define DEST_CHARSET “UTF-8”<br />
    

    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:

    NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
    NSData *data = [NSData dataWithContentsOfURL:url];
    if (data != nil)
        NSLog(@"Device is connected to the internet");
    else
        NSLog(@"Device is not connected to the internet");
    

    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.

  • Title For Navigation Controller In Tab Controller

    If you just set only a self.title and self.tabBarItem.title, your tabBarItem title will change to the title of navigation controller.
    So, this is the solution, taken from StackOverflow:

    self.title = @"Title for TabBarItem";
     // TabBarItem.title inherits the viewController's self.title
    self.navigationItem.title = @"Title for NavigationBar";
    
  • Two NSStrings are same but different when you compare them

    Recently I was shocked by the fact that two NSStrings that resemble each other on NSLog may be different. It is because sometimes NSString can contain a zero width space character. Be aware of that and consider:

        #define ZERO_WIDTH_SPACE_STRING @"\u200B"
    

    To conquer this you should clean your string from zero width white space characters before comparing:

        NSMutableString *eMailToAdd = [NSMutableString string];
    	
        NSMutableCharacterSet *charSet = \
    [[NSCharacterSet whitespaceCharacterSet] mutableCopy];
        	//[charSet formUnionWithCharacterSet:\
    [NSCharacterSet punctuationCharacterSet]];
        	
            NSString *rawStr = [[tokenField textField] text];
        	for (int i = 0; i < [rawStr length]; i++)
        	{
        		if (![charSet characterIsMember:\
    [rawStr characterAtIndex:i]])
        		{
        			[eMailToAdd appendFormat:\
    @"%@",[NSString stringWithFormat:@"%c",\
     [rawStr characterAtIndex:i]]];
        		}
        	}
    
  • How to hide a keyboard from view

    Sometimes it is hard to use resignFirstResponder method on every textField, that is present on our view. It is much easier to hide keyboard by the following way:

    [self.view endEditing:YES];
    
  • Delete button title in table view iOS

    To change a delete button title use this:

    - (NSString *)tableView:(UITableView *)tableView \
     titleForDeleteConfirmationButtonForRowAtIndexPath: \
    (NSIndexPath *)indexPath {
        
        return @"Удалить из избранного";
        
    }
    
  • Grouped table view background color

    To change a background color of a grouped table view in iOS we need to do two things:

    self.tableView.backgroundColor = your_color;
    self.tableView.backgroundView = nil;
    

    It is the third answer here.

  • UIView animation pattern

    Animation pattern using blocks:

        [UIView animateWithDuration:1.0
                         animations:^{
                             
                         }
                         completion:^(BOOL finished){
                             
                         }
         ];
    
  • How to create an animated Intro View in iOS

    I will explain, how to create an animation, when you Default image comes to front with dissolving.

    To create an animated Intro View in iOS App, which has a TabBarController you may do the following:

      1. Create an Intro View Controller, which has one UIImageView with your Default.png.
      2. Add the following to your application didFinishLaunchingWithOptions method
        IntroViewController *introViewController = \
        [[IntroViewController alloc] initWithNibName: \
        @"IntroViewController" bundle:nil];
            self.window.rootViewController = introViewController;
            
            [self.window makeKeyAndVisible];
        
      3. Add the following method to your IntroViewController:
        - (void)viewDidAppear:(BOOL)animated
        {
            [super viewDidAppear:animated];
            
            [UIView animateWithDuration:0.5
                             animations:^{
                                 CGRect frame = self.imageView.frame;
                                 frame.origin.x -= frame.size.width;
                                 frame.origin.y -= frame.size.height;
                                 frame.size.width *= 3;
                                 frame.size.height *= 3;
                                 self.imageView.frame = frame;
                                 self.imageView.alpha = 0.0;
                             }
                             completion:^(BOOL finished){
                                 useDelegate
                                 appDelegate.window.rootViewController = \
        appDelegate.tabBarController;
                             }
            ];
        }
        

      Explanation:
      After app loads, Intro View Controller is diplayed. Then, when it’s view appears, it’s UIImageView’s frame is trippled in size and it’s origin is moved to top left. Also the transparency is changed to 100%. After animation finishes, your tab bar controller is displayed.