Tuesday, December 15, 2015

How to show HashTags in Comments or Post same as FB, Twitter and Instagram in iOS


How to ADD HasTag in TextView

UITextView * myTextView = [[UITextView alloc] init];
[myTextView setAttributedText:[self attributedMessageFromMessage: myTextView.text]];

NSArray * hashTagsArray = [NSArray arrayWithObjects:@"Apple"@"Google"@"Microsoft",@"Yahoo"@"Microsoft Google"@"Google Apple",  nil];

//Add Tap Gesture in TextView for gives action to HashTags
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:selfaction:@selector(messageTapped:)];
tap.numberOfTapsRequired = 1;
[myTextView addGestureRecognizer:tap];

//This method is used for showing color in HashTags according to its Array. Its only show on color on tags which is in array.
- (NSAttributedString *)attributedMessageFromMessage:(NSString *)message
{
    NSArray* messageWords = [message componentsSeparatedByString@" "];
    NSMutableAttributedString *attributedMessage = [[NSMutableAttributedString alloc]initWithString:@""];
    
    for (NSString *word in messageWords)
    {
        NSDictionary * attributes;
        if (word.length>0) {
            
        
        if([word characterAtIndex:0] == '@')
        {
            if ([hashTagsArray containsObject:[word substringFromIndex:1]])
            {
                attributes = @{NSForegroundColorAttributeName:[UIColor blueColor],
                               wordTypeuserNameKey,
                               userNameKey:[word substringFromIndex:1]};
            }
            else
            {
                attributes = @{NSForegroundColorAttributeName:[UIColor blackColor],wordTypenormalKey};
            }
            
        }
        else if([word characterAtIndex:0] == '*')
        {
           if ([hashTagsArray containsObject:[word substringFromIndex:1]])
            {
                attributes = @{NSForegroundColorAttributeName:[UIColor blueColor],
                               wordTypehashTagKey,
                               hashTagKey:[word substringFromIndex:1]};
            }
            else
            {
                attributes = @{NSForegroundColorAttributeName:[UIColor blackColor],wordTypenormalKey};
            }
            
        }
        
        else
        {
            attributes = @{NSForegroundColorAttributeName:[UIColor blackColor], wordType:normalKey};
        }
            
        NSAttributedString * subString = [[NSAttributedString alloc]
                                          initWithString:[NSString stringWithFormat:@"%@ ",word]
                                          attributes:attributes];
        [attributedMessage appendAttributedString:subString];
        }
    }

    return attributedMessage;
}

//This method is used to find which HashTag is tapped
- (IBAction)messageTapped:(UITapGestureRecognizer *)recognizer
{
    UITextView *textView = (UITextView *)recognizer.view;
    textView.selectable = YES;
    NSLayoutManager *layoutManager = textView.layoutManager;
    CGPoint location = [recognizer locationInView:textView];
    location.x -= textView.textContainerInset.left;
    location.y -= textView.textContainerInset.top;
    
    
    NSUInteger characterIndex;
    characterIndex = [layoutManager characterIndexForPoint:location
                                           inTextContainer:textView.textContainer
                  fractionOfDistanceBetweenInsertionPoints:NULL];
    
    textView.selectable = NO;
    
    if (characterIndex < textView.textStorage.length)
    {
        NSRange range;
        id type = [textView.attributedText attribute:wordType
                                             atIndex:characterIndex
                                      effectiveRange:&range];
        
        if([type isEqualToString:userNameKey])
        {
            NSString *userName = [textView.attributedText attribute:userNameKey
                                                            atIndex:characterIndex
                                                     effectiveRange:&range];
            [self hashTagBtnAction:userName];
        }
        else if([type isEqualToString:hashTagKey])
        {
            NSString *userName = [textView.attributedText attribute:hashTagKey
                                                            atIndex:characterIndex
                                                     effectiveRange:&range];
            [self hashTagBtnAction:userName];
        }
    }
}

//This method is used for gives action on HashTags.
-(void)hashTagBtnAction:(NSString *)str
{
     NSLog(@"You tap on %@ Tag", str);
     //code here......

}

How to add HashTags in Comments or Post same as FB, Twitter and Instagram in iOS




WUTextSuggestionController aims to be a full featured text suggestion toolkit for iOS.
It can easily be integrated in your project with only couple lines of code. It allows you to load text suggestions asynchronously from a remote server. It is fully customizable. You can design your own text suggestion display controller to work with it.
it currently supports @ (at) and # (hashtag, twitter style) suggestions for UITextView.

WUTextSuggestionController is a text suggestion toolkit for iOS.
ScreenShot
Download and run the demo project to see it in action.

How to implement UIRefreshControl in a UIScrollView in iOS




- (void)viewDidLoad
{
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)];
    scrollView.userInteractionEnabled = TRUE;
    scrollView.scrollEnabled = TRUE;
    scrollView.backgroundColor = [UIColor whiteColor];
    scrollView.contentSize = CGSizeMake(500, 1000);

    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
    [refreshControl addTarget:self action:@selector(testRefresh:) forControlEvents:UIControlEventValueChanged];
    [scrollView addSubview:refreshControl];

    [self.view addSubview:scrollView];
}

- (void)testRefresh:(UIRefreshControl *)refreshControl
{    
    refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"Refreshing data..."];

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        [NSThread sleepForTimeInterval:3];

        dispatch_async(dispatch_get_main_queue(), ^{
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"MMM d, h:mm a"];
            NSString *lastUpdate = [NSString stringWithFormat:@"Last updated on %@", [formatter stringFromDate:[NSDate date]]];

            refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:lastUpdate];

            [refreshControl endRefreshing];

            NSLog(@"refresh end");
        });
    });
}

Need to do the data update on a separate thread or it will lock up the main thread (which the UI uses to update the UI). So while the main thread is busy updating the data, the UI is also locked up or frozen and you never see the smooth animations or spinner.

How to implement lazy loading in iOS SDK


Following suggest how to lazyloading in iOS Development 


Download SDWebImage SDK :-

Unzip this folder and add all files from SDWebImage folder to your project.

When you add the SDWebImage folder in your project then select following option. To add copy of your folder to the destination project and Create groups.

and then you have to write just like


#import "UIImageView+WebCache.h"
and call the this method:-

[self.imageView sd_setImageWithURL:[NSURL URLWithString:"yoururl.png"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
It provides:
  • An UIImageView category adding web image and cache management
  • An asynchronous image downloader
  • An asynchronous memory + disk image caching with automatic cache expiration handling
  • Animated GIF support
  • A background image decompression
  • A guarantee that the same URL won't be downloaded several times
  • A guarantee that bogus URLs won't be retried again and again
  • A guarantee that main thread will never be blocked
  • Performances!

How to create Forgot Password Default Alert Popup for all iOS Apps



//Declare in .h file
NSString * forgotPasswordAlertText;

//Forgot Password button Actions Methods
- (IBAction)forgotPasswordButtonTapped:(id)sender{

    UIAlertView * altView = [[UIAlertView allocinitWithTitle:@"Forgot Password?"message:@"Please enter your email address." delegate:self cancelButtonTitle:@“Cancel"otherButtonTitles:@"OK"nil];
    altView.tag = 101;
    [altView setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [altView textFieldAtIndex:0].placeholder = @"Email Address";
    [altView textFieldAtIndex:0].keyboardType = UIKeyboardTypeEmailAddress;
    [altView textFieldAtIndex:0].returnKeyType = UIReturnKeyDone;
    [altView textFieldAtIndex:0].text = forgotPasswordAlertText;
    [altView show];
}

#pragma mark Alert view Delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (alertView.tag) {
        //101 tag for forgot password
        case 101:
            switch (buttonIndex) {
                case 1:
                    forgotPasswordAlertText = [alertView textFieldAtIndex:0].text;
                    if (![self validateEmail:forgotPasswordAlertText]){
                        showAlertOkAction@"Check Email"@"Please Enter Proper Username");
                    }else{
                        //call web service method from here
                        forgotPasswordAlertText = @"";
                    }
                    break;
                    
                default:
                    break;
            }
            break;
        //102 tag for reopen forgot password alert
        case 102:
            [self forgotPasswordButtonTapped:nil];
            
        default:
            break;
    }
}

//For Email Validation

-(BOOL)validateEmail:(NSString*)email{
    
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    BOOL isValid = [emailTest evaluateWithObject:email];
    
    return isValid;
}


//Declare in Constant File


#define showAlertOkAction(messageT,title) UIAlertView *alert=[[UIAlertView alloc] initWithTitle:messageT message:title delegate:nil cancelButtonTitle:@"OK"otherButtonTitles:nil, nil];[alert show];alert.tag = 102;alert.delegate = self;

Screenshots size for upload application to App Server in iOS (ALL Device)



The iPhone 6 and iPhone 6 Plus screenshots don't accept cropped (without status bar) uploads.

5.5in (iPhone 6 Plus):
1242 × 2208px portrait

4.7in (iPhone 6):
750 × 1334px portrait

4in (iPhone 5 and 5s):
640 × 1096px portrait (without status bar) minimum
640 × 1136px portrait (full screen) maximum
1136 × 600px landscape (without status bar) minimum
1136 × 640px landscape (full screen) minimum

3.5in (iPhone 4 and 4s):
640 × 920px portrait (without status bar) minimum
640 × 960px portrait (full screen) maximum
960 × 600px landscape (without status bar) minimum
960 × 640px landscape (full screen) maximum