Thursday, May 30, 2013

Face Detection Example in iOS

Here in this Example i will show how to detect face on image.

Here we need two framework CoreImage & QuartzCore.
Let Start.
.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (retain, nonatomic) IBOutlet UIButton *btnScanFace;
- (IBAction)btnScanFace:(id)sender;
@property (retain, nonatomic) IBOutlet UIImageView *imgView;
@end

.m
#import "ViewController.h"
#import <CoreImage/CoreImage.h>
#import <QuartzCore/QuartzCore.h>


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.imgView.image=[UIImage imageNamed:@"family.png"];
}

- (IBAction)btnScanFace:(id)sender {
 // draw a CI image with the previously loaded picture
    CIImage* image1=[CIImage imageWithCGImage:self.imgView.image.CGImage];
 // create a face detector - since speed is not an issue we'll use a high accuracy

    // detector


    CIDetector* detector1=[CIDetector detectorOfType:CIDetectorTypeFace context:nil options:[NSDictionary dictionaryWithObject:CIDetectorAccuracyHigh forKey:CIDetectorAccuracy]];
// create an array containing all the detected faces from the detector  

    NSArray *feature1=[detector1 featuresInImage:image1];
    NSLog(@"%d",[feature1 count]);
// Here i use frameview because ciimage and uiimage are inversely if we leave as it is than detection will occur but show in different direction. 
    UIView *frameview=[[UIView alloc] initWithFrame:CGRectMake(self.imgView.bounds.origin.x, self.imgView.bounds.origin.y, self.imgView.image.size.width, self.imgView.image.size.height)];

 // we'll iterate through every detected face.  CIFaceFeature provides us
    // with the width for the entire face, and the coordinates of each eye
    // and the mouth if detected.  Also provided are BOOL's for the eye's and
    // mouth so we can check if they already exist.

    for (CIFaceFeature * faceFeature1 in feature1) {

// create a UIView using the bounds of the face
        //UIView* faceView1 = [[UIView alloc] initWithFrame:faceFeature.bounds];
UIView *faceView1=[[UIView alloc]initWithFrame:CGRectMake(faceFeature1.bounds.origin.x, faceFeature1.bounds.origin.y-15, faceFeature1.bounds.size.width, faceFeature1.bounds.size.height + 40)];

// Border is set
faceView1.layer.borderWidth=1;
faceView1.layer.borderColor=[[UIColor blackColor] CGColor];
[frameview addSubview:faceView1];
}

    [frameview setTransform:CGAffineTransformMakeScale(1, -1)];
    [self.view addSubview:frameview];
}











Thursday, May 23, 2013

Play YouTube Embedded Video in WebView on UiButton Click

In this Example I will Show you how to play YouTube Video embedded in WebView on Button Click.
Just we have to find Button within WebView and Trigger it.

Here is the Code.
.h

#import <UIKit/UIKit.h>
@interface RSSDetailViewController : UIViewController <UIWebViewDelegate,UIScrollViewDelegate> 
@property (nonatomic, retain) IBOutlet UIWebView *webViewLink; 
- (IBAction)btnPlay:(id)sender; 
@end

.m
// self.link is link of youtube video.
- (void)viewDidLoad
{
 [self.webViewLink loadRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:self.link]]];
}

- (UIButton *)findButtonInView:(UIView *)view {
    UIButton *button = nil;
    
    if ([view isMemberOfClass:[UIButton class]]) {
        return (UIButton *)view;
    }
    
    if (view.subviews && [view.subviews count] > 0) {
        for (UIView *subview in view.subviews) {
            button = [self findButtonInView:subview];
            if (button) return button;
        }
    }
    
    return button;
}
- (IBAction)btnPlay:(id)sender {
    UIButton *btnTouch=[self findButtonInView:webViewLink];
    [btnTouch sendActionsForControlEvents:UIControlEventTouchUpInside];
}

Reference
:http://stackoverflow.com/questions/3010708/youtube-video-autoplay-on-iphones-safari-or-uiwebview

Monday, May 20, 2013

Fixed the Position of UiWebView Scrolling in iOS

Here in this Example i will show you how to restrict the movement of scrollbar in UiWebView at particular point.

We have to set delegate of UiWebView scroll to call UiScrollView Method.

Let Start.
.h


#import <UIKit/UIKit.h>

#import "AsyncImageView.h"

@interface RSSDetailViewController : UIViewController <UIWebViewDelegate,UIScrollViewDelegate>
@property (nonatomic, retain) IBOutlet UIWebView *webViewLink;

@end

.m

@synthesize webViewLink;
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.webViewLink.scrollView.delegate=self;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSLog(@"scrolling vertically; %f",scrollView.contentOffset.y);
    if(scrollView.contentOffset.y> 52)
    {
        CGPoint offSet=scrollView.contentOffset;
        offSet.y=52;
        [scrollView setContentOffset:offSet];
    }
}

IT will restrict the UiWebView scroll at point when it reach to 52

Thursday, May 9, 2013

Asynchronous Load Image in UiTableView Cell

In this Example i will show how to load image from url Asynchronously which reduce load time.

There are two Method
Now Let Start.

I think there is no need to tell how to take TableView, just start with UiTableViewCell code.
Method 1. .h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>

@property (retain, nonatomic) IBOutlet UITableView *tblview;
@property(retain,nonatomic)NSArray *aryImageUrl;
@end

.m
- (void)viewDidLoad

{

[super viewDidLoad];
 self.aryImageUrl =[NSArray arrayWithObjects:@"url1",@"url2",@"url3",@"url4",@"url5", nil];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.aryImageUrl count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *str=@"cell";
    
    UITableViewCell *celltbl=[tableView dequeueReusableCellWithIdentifier:str];
    if(celltbl==nil)
    {
        celltbl=[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str] autorelease];
    }
    
    NSURL *url=[NSURL URLWithString:[self.aryImageUrl objectAtIndex:[indexPath row]]];
    NSURLRequest *req=[NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *err) {
        celltbl.imageView.image=[UIImage imageWithData:data];
    }];
    
    return celltbl;
    
}

Explanation:
NSURLRequest  : NSURLRequest objects represent a URL load request in a manner independent of protocol and URL scheme.


NSURLConnection :An NSURLConnection object provides support to perform the loading of a URL request. The interface for NSURLConnection is sparse, providing only the controls to start and cancel asynchronous loads of a URL request.


sendAsynchronousRequest :

Loads the data for a URL request and executes a handler block on an operation queue when the request completes or fails.
If the request completes successfully, the data parameter of the handler block contains the resource data, and the error parameter is nil. If the request fails, the data parameter is nil and the error parameter contain information about the failure.

Parameters:
request
The URL request to load. The request object is deep-copied as part of the initialization process. Changes made to request after this method returns do not affect the request that is used for the loading process.
queue
The operation queue to which the handler block is dispatched when the request completes or failed.
handler
The handler block to execute.

Method 2.
In this method i have used class method for asychronous call.

.h
#import <Foundation/Foundation.h>
@interface WebImageOperation : NSObject
+(void)processImageWithUrlString:(NSString *)urlString andBlock:(void(^)(NSData * imageData))processImage;

@end

.m 

#import "WebImageOperation.h"
#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
@implementation WebImageOperation
+(void)processImageWithUrlString:(NSString *)urlString andBlock:(void(^)(NSData * imageData))processImage
{

    NSURL *url=[NSURL URLWithString:urlString];
    dispatch_queue_t callerQuere=dispatch_get_current_queue();
    dispatch_queue_t downloadQueue=dispatch_queue_create("com.dresscodefinder.processimagequeue", NULL);
    dispatch_async(downloadQueue, ^{
        NSData *imageData=[NSData dataWithContentsOfURL:url];
       dispatch_async(callerQuere, ^{
           processImage(imageData);
       });
    });

    dispatch_release(downloadQueue);
}
@end


dispatch_queue_t: A dispatch queue is a lightweight object to which your application submits blocks for subsequent execution.

dispatch_async:Submits a block for asynchronous execution on a dispatch queue and returns immediately

Now in tableview call this class method inside cellForRowAtIndexPath

[WebImageOperation processImageWithUrlString:info.imageCache andBlock:^(NSData *imageData) {
        UIImage *image=[UIImage imageWithData:imageData];
        cell.imageView.image=image;
     
    }];