UIButton inheritance doesnt show image - objective-c

I am trying to make an inheritance of a UIButton. Which if clicked will play a sound , scales up. And when finishes playing sound scales back to the original state.
Everything is working except the image is not showing.
The title and background do scale up, and the sound is being played.
Anyone a hint?
soundButton.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#interface soundButton : UIButton <AVAudioRecorderDelegate, AVAudioPlayerDelegate>{
BOOL isPlaying;
AVAudioPlayer *audioPlayer;
}
#property (nonatomic)BOOL isPlaying;
#property (nonatomic, strong) AVAudioPlayer *audioPlayer;
- (id)initWithFrame:(CGRect)frame;
-(void)loadSound:(NSString*)audiofile;
-(void)touchUpInside;
#end
soundButton.m
#import "soundButton.h"
#implementation soundButton
#synthesize isPlaying;
#synthesize audioPlayer;
void audioRouteChangeListenerCallback (
void *inUserData,
AudioSessionPropertyID inPropertyID,
UInt32 inPropertyValueSize,
id *inPropertyValue);
-(BOOL)isPlaying{
return audioPlayer.isPlaying;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self addTarget:self action:#selector(touchUpInside) forControlEvents:UIControlEventTouchUpInside];
UIImage *image = [UIImage imageNamed:#"kers.png"];
[self setBackgroundImage:image forState:UIControlStateNormal];
}
return self;
}
-(void)loadSound:(NSString*)audiofile{
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:audiofile
ofType:nil]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
if (error)
{
NSLog(#"Error in audioPlayer: %#",
[error localizedDescription]);
} else {
audioPlayer.delegate = self;
[audioPlayer setVolume:1.0];
[audioPlayer prepareToPlay];
audioPlayer.currentTime = 0;
}
}
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
[audioPlayer setCurrentTime:0];
self.transform = CGAffineTransformMakeScale(1.5,1.5);
self.alpha = 1.0f;
[UIView beginAnimations:#"fish" context:nil];
[UIView setAnimationDuration:1];
self.transform = CGAffineTransformMakeScale(1.0,1.0);
self.alpha = 1.0f;
[UIView commitAnimations];
self.isPlaying = NO;
}
-(void)touchUpInside{
//Check if something is playing If YES=>stop it
if (self.isPlaying) {
[audioPlayer stop];
[audioPlayer setCurrentTime:0];
} else {
self.transform = CGAffineTransformMakeScale(1.0,1.0);
self.alpha = 1.0f;
[UIView beginAnimations:#"fish" context:nil];
[UIView setAnimationDuration:1];
self.transform = CGAffineTransformMakeScale(1.5,1.5);
self.alpha = 1.0f;
[UIView commitAnimations];
}
// Create an asynchronous background queue
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperationWithBlock:
^{
[audioPlayer play];
}];
}
#end
implemented in ViewdidLoad in the viewController:
UIImage *image = [[UIImage alloc]initWithContentsOfFile:#"cherry.png"];
fishButton = [[soundButton alloc] initWithFrame:CGRectMake(323, 312, 123, 123)];
[fishButton setImage:image forState:UIControlStateNormal];
[fishButton loadSound:#"chime1.mp3"];
[fishButton setTitle:#"fish" forState:UIControlStateNormal];
[fishButton setBackgroundColor:[UIColor yellowColor]];
[fishButton setShowsTouchWhenHighlighted:YES];
[self.view addSubview:fishButton];

replace this
UIImage *image = [[UIImage alloc]initWithContentsOfFile:#"cherry.png"];
with this
UIImage *image = [UIImage imageNamed:#"cherry.png"];
or if you really need to use initWithContentsOfFile use URL link like
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"cherry" ofType:#"png"];
UIImage *image = [[UIImage alloc]initWithContentsOfFile:filePath];

Related

uiview animatewithduration completion continues after view is dismissed

I have a modelViewController that contains a UIView animation. When the animation block finishes it calls itself, thus looping.
When I dismiss the modelViewController (dismissInfo) which calls [_starView removeFromSuperview], the function gets called over and over very rapidly with the NSLog line being printed multiple times a second.
#implementation InfoVC
{
NSArray *imgs;
NSString *currentImg;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_imageview.contentMode = UIViewContentModeLeft;
_imageviewUnder.contentMode = UIViewContentModeLeft;
imgs = [NSArray arrayWithObjects:
#"01.jpg",
#"02.jpg",
#"03.jpg",
#"04.jpg",
#"05.jpg",
#"06.jpg",
nil];
_imgInt = (arc4random()%6);
[self initialImage];
}
- (void)viewWillAppear:(BOOL)animated{
}
- (void)viewDidAppear:(BOOL)animated{
NSLog(#"viewDidAppear");
}
- (void)initialImage
{
_starView.contentMode = UIViewContentModeLeft;
_imageviewUnder.contentMode = UIViewContentModeLeft;
currentImg = [imgs objectAtIndex:_imgInt];
UIImage *image = [UIImage imageNamed:currentImg];
_starView = [[UIImageView alloc] initWithImage:image];
// Size the image view to the image (it's bigger)
_starView.bounds = CGRectMake(0.0, 44.0, 416.0, 416.0);
NSLog(#"tarView.center %#", NSStringFromCGPoint(_starView.center) );
_starView.alpha=1;
int nextImgInt = _imgInt + 1 ;
if (nextImgInt>5)
{
nextImgInt=0;
}
NSString *nextImg = [imgs objectAtIndex:nextImgInt];
UIImage *nextImage = [UIImage imageNamed:nextImg];
[_imageviewUnder setImage:nextImage];
[self.view sendSubviewToBack:_imageviewUnder];
_imgInt++;
if (_imgInt>5) {
_imgInt=0;
}
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView animateWithDuration:7.6f
delay:0.1f
options:UIViewAnimationCurveLinear
animations:^{
[_starView setCenter:CGPointMake(112, 208)];
[_starView setAlpha:0.0f];
}
completion:^(BOOL finished){
[_starView removeFromSuperview];
[self initialImage];
}];
[self.view insertSubview:_starView atIndex:1];
}
- (void)visitTwitter
{
NSURL *URL = [NSURL URLWithString:#"http://twitter.com/"];
SVWebViewController *webViewController = [[SVWebViewController alloc] initWithURL:URL];
[self.navigationController pushViewController:webViewController animated:YES];
}
- (IBAction)dismissInfo:(id)sender
{
[self cleanup];
[self dismissModalViewControllerAnimated:YES];
}
- (void)cleanup
{
[_starView.layer removeAllAnimations];
[self.view.layer removeAllAnimations];
[_starView removeFromSuperview];
}
- (void)viewDidUnload
{
[self cleanup];
[super viewDidUnload];
}
#end
Make yourself an animating flag, set true in viewDidLoad, and false in cleanup. Then check it in your initialImage method:
if ( ! animating )
return;
This is the second time I've come across this. One possible cause is the method being initialised in viewDidLoad but the subview and image not being ready in time (it seems the first pass of the animation loop doesn't work adding a ghost to the machine).
I moved the call to ViewDidAppear, making sure to display an initialisation image to stop the white flash. At last an infinite animation in a modal window
- (void)viewDidLoad
{
[super viewDidLoad];
_imageview.contentMode = UIViewContentModeLeft;
_imageviewUnder.contentMode = UIViewContentModeLeft;
imgs = [NSArray arrayWithObjects:
#"01.jpg",
#"02.jpg",
#"03.jpg",
#"04.jpg",
#"05.jpg",
#"06.jpg",
nil];
_imgInt = (arc4random()%6);
currentImg = [imgs objectAtIndex:_imgInt];
UIImage *image = [UIImage imageNamed:currentImg];
[_imageviewUnder setImage:image];
}
- (void)viewDidAppear:(BOOL)animated{
[self initialImage];
}
- (void)initialImage
{
currentImg = [imgs objectAtIndex:_imgInt];
UIImage *image = [UIImage imageNamed:currentImg];
_starView = [[UIImageView alloc] initWithImage:image];
// Size the image view to the image (it's bigger)
_starView.bounds = CGRectMake(0.0, 44.0, 416.0, 416.0);
NSLog(#"initialImage");
_starView.alpha=1;
[self.view insertSubview:_starView atIndex:1];
int nextImgInt = _imgInt + 1 ;
if (nextImgInt>5)
{
nextImgInt=0;
}
NSString *nextImg = [imgs objectAtIndex:nextImgInt];
UIImage *nextImage = [UIImage imageNamed:nextImg];
[_imageviewUnder setImage:nextImage];
[self.view sendSubviewToBack:_imageviewUnder];
_imgInt++;
if (_imgInt>5) {
_imgInt=0;
}
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:7.6];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
//[UIView setAnimationDidStopSelector:#selector(initialImage) ];
[_starView setCenter:CGPointMake(112, 208)];
[_starView setAlpha:0.0f];
[UIView commitAnimations];
[self performSelector:#selector(initialImage) withObject:nil afterDelay:7.6];
}
- (IBAction)dismissInfo:(id)sender
{
[self cleanup];
[self dismissModalViewControllerAnimated:YES];
}
- (void)cleanup
{
[NSObject cancelPreviousPerformRequestsWithTarget:self];
[_starView.layer removeAllAnimations];
[self.view.layer removeAllAnimations];
[_starView removeFromSuperview];
}
If you just want to create a looping animation, the best thing to do is use the option: 'UIViewAnimationOptionRepeat'. For example:
[UIView animateWithDuration:2.0
delay:0.0f
options:UIViewAnimationOptionRepeat
animations:^{
[myUIViewThing setCenter:CGPointMake(myUIViewThing.center.x - 100, myUIViewThing.center.y)];
}
completion:nil];

Issue in previewing the video using AVFoundation and MPMovieController at a time in iphone sdk

I am Using AVFoundation's AVCaptureSession to capture the video and I am using the MPMoviePlayerController to play the streamed url(video) from server. When I am capturing only video with AVCaptureSession there is no problem. But When I tried to play the streamed url(with MPMoviePlayerController) along with capturing of video with AVCaptureSession at a time the problem occurs as the capturing from AVCaptureSession stops.
This is what I had done:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication ]delegate];
if([appDelegate isIpad] == YES)
controlsView = [[UIView alloc] initWithFrame:CGRectMake(self.view.bounds.origin.x+200, self.view.bounds.origin.y+250, self.view.bounds.size.width, self.view.bounds.size.height)];
else
controlsView = [[UIView alloc] initWithFrame:self.view.bounds];
controlsView.backgroundColor = [UIColor blackColor];
[self.view addSubview:controlsView];
[self.view sendSubviewToBack:controlsView];
//settingsBtn = [[UIButton alloc]initWithFrame:CGRectMake(10,400, 50, 50)];
settingsBtn = [[UIButton alloc]initWithFrame:CGRectMake(10,400, 50, 50)];
[settingsBtn setImage:[UIImage imageNamed:#"settings.png"] forState:UIControlStateNormal];
[settingsBtn addTarget:self action:#selector(settingsAction) forControlEvents:UIControlEventTouchUpInside];
[controlsView addSubview:settingsBtn];
callButton = [[UIButton alloc]initWithFrame:CGRectMake(260,400, 50, 50)];
if(isCallButtonClicked ==NO)
[callButton setImage:[UIImage imageNamed:#"call.png"] forState:UIControlStateNormal];
else
[callButton setImage:[UIImage imageNamed:#"callEnd.png"] forState:UIControlStateNormal];
[callButton addTarget:self action:#selector(callAction) forControlEvents:UIControlEventTouchUpInside];
[controlsView addSubview:callButton];
statusLabel = [[UILabel alloc]initWithFrame:CGRectMake(120, 20, 150, 40)];
statusLabel.textColor = [UIColor whiteColor];
statusLabel.backgroundColor = [UIColor clearColor];
statusLabel.textAlignment = UITextAlignmentLeft;
statusLabel.font = [UIFont boldSystemFontOfSize:20];
dot1 = [[UIView alloc] initWithFrame:CGRectMake(75, 20, 7, 7)];
dot1.layer.cornerRadius = 5;
dot1.backgroundColor = [UIColor whiteColor];
[statusLabel addSubview:dot1];
dot2 = [[UIView alloc] initWithFrame:CGRectMake(84, 20, 7, 7)];
dot2.layer.cornerRadius = 5;
dot2.backgroundColor = [UIColor whiteColor];
[statusLabel addSubview:dot2];
dot3 = [[UIView alloc] initWithFrame:CGRectMake(93, 20, 7, 7)];
dot3.layer.cornerRadius = 5;
dot3.backgroundColor = [UIColor whiteColor];
[statusLabel addSubview:dot3];
downStreamView = [[UIView alloc]initWithFrame:CGRectMake(controlsView.bounds.origin.x, controlsView.bounds.origin.y, controlsView.bounds.size.width, controlsView.bounds.size.height - 70)];
[[controlsView layer] addSublayer:downStreamView.layer];
downStreamView.layer.backgroundColor = [UIColor greenColor].CGColor;
AVCaptureSession *captureSession = [[AVCaptureSession alloc]init];
NSError *error;
/* getting the device input */
AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:[self frontFacingCamera] error:&error];
if(error)
{
NSLog(#"%#",#"Could not create video input");
}
[captureSession addInput:videoInput];
AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:[self audioDevice] error:&error];
[captureSession addInput:audioInput];
audioOutput = [[AVCaptureAudioDataOutput alloc]init];
[captureSession addOutput:audioOutput];
previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:captureSession];
[previewLayer setFrame:CGRectMake(controlsView.bounds.origin.x, controlsView.bounds.origin.y, controlsView.bounds.size.width, controlsView.bounds.size.height - 70)];
[previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[[controlsView layer] addSublayer:previewLayer];
[captureSession startRunning];
}
//make call Action
-(void)makeCallAction
{
if(isCallButtonClicked == NO)
{
statusLabel.text = #"Dialling";
[controlsView addSubview:statusLabel];
if(!isAnimationStarted)
[self animate];
[callButton setImage:[UIImage imageNamed:#"callEnd.png"] forState:UIControlStateNormal];
[UIView animateWithDuration:2.0
animations:^{
CGRect frame = CGRectMake(downStreamView.layer.bounds.origin.x, downStreamView.layer.bounds.size.height-100, 100, 100);
previewLayer.frame = frame;
[downStreamView.layer addSublayer:previewLayer];
}
completion:^(BOOL finished){
//Do nothing
}];
isCallButtonClicked = YES;
}
else if(isCallButtonClicked == YES)
{
[statusLabel removeFromSuperview];
[callButton setImage:[UIImage imageNamed:#"call.png"] forState:UIControlStateNormal];
[UIView animateWithDuration:2.0
animations:^{
[previewLayer setFrame:CGRectMake(controlsView.bounds.origin.x, controlsView.bounds.origin.y, controlsView.bounds.size.width, controlsView.bounds.size.height - 70)];
[[controlsView layer] addSublayer:previewLayer];
}
completion:^(BOOL finished){
//Do nothing
}];
isCallButtonClicked = NO;
}
}
//Settings Action
-(void)settingsAction
{
NSString *nibName = nil;
if ([[[UIDevice currentDevice] model] isEqualToString:#"iPhone"] || [[[UIDevice currentDevice] model] isEqualToString:#"iPhone Simulator"]) {
nibName = #"SettingsViewController";
}
else {
nibName = #"SettingsViewController_iPad";
}
SettingsViewController *settingsController = [[SettingsViewController alloc]initWithNibName:nibName bundle:nil];
[self.navigationController presentModalViewController:settingsController animated:YES];
}
-(void)callAction
{
NSURL *theMovieURL = [NSURL URLWithString:#"someURL.m3u8"];
if (theMovieURL)
{
if ([theMovieURL scheme]) // sanity check on the URL
{
/* Play the movie with the specified URL. */
[self playStreamingURL:theMovieURL];
}
}
[self makeCallAction];
}
-(void)playStreamingURL:(NSURL *)aUrlStr
{
MPMovieSourceType movieSourceType = MPMovieSourceTypeUnknown;
/* If we have a streaming url then specify the movie source type. */
if ([[aUrlStr pathExtension] compare:#"m3u8" options:NSCaseInsensitiveSearch] == NSOrderedSame)
{
movieSourceType = MPMovieSourceTypeStreaming;
}
[self createAndPlayMovieForURL:aUrlStr sourceType:movieSourceType];
}
-(void)createAndPlayMovieForURL:(NSURL *)movieURL sourceType:(MPMovieSourceType)sourceType
{
[self createAndConfigurePlayerWithURL:movieURL sourceType:sourceType];
/* making the player to be visible in full screen mode */
//if(!self.moviePlayerController.fullscreen)
// self.moviePlayerController.fullscreen = YES;
/* disabling the controls of the movie player */
self.moviePlayerController.controlStyle = MPMovieControlStyleNone;
/* Play the movie! */
[[self moviePlayerController] play];
}
-(void)createAndConfigurePlayerWithURL:(NSURL *)movieURL sourceType:(MPMovieSourceType)sourceType
{
[controlsView addSubview:downStreamView];
/* Create a new movie player object. */
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
if (player)
{
/* Save the movie object. */
[self setMoviePlayerController:player];
player.contentURL = MPMovieControlStyleNone;
//if(!player.fullscreen)
// player.fullscreen = YES;
/* Register the current object as an observer for the movie
notifications. */
// [self installMovieNotificationObservers];
/* Specify the URL that points to the movie file. */
[player setContentURL:movieURL];
/* If you specify the movie type before playing the movie it can result
in faster load times. */
[player setMovieSourceType:sourceType];
/* Apply the user movie preference settings to the movie player object. */
//[self applyUserSettingsToMoviePlayer];
/* Add a background view as a subview to hide our other view controls
underneath during movie playback. */
//CGRect viewInsetRect = CGRectInset ([self.view bounds],
// kMovieViewOffsetX,
//kMovieViewOffsetY );
/* Inset the movie frame in the parent view frame. */
[[player view] setFrame:downStreamView.bounds];
[player view].backgroundColor = [UIColor redColor];
/* To present a movie in your application, incorporate the view contained
in a movie player’s view property into your application’s view hierarchy.
Be sure to size the frame correctly. */
[downStreamView.layer addSublayer: [player view].layer];
}
}
-(void)installMovieNotificationObservers
{
MPMoviePlayerController *player = [self moviePlayerController];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(loadStateDidChange:)
name:MPMoviePlayerLoadStateDidChangeNotification
object:player];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:player];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(mediaIsPreparedToPlayDidChange:)
name:MPMediaPlaybackIsPreparedToPlayDidChangeNotification
object:player];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayBackStateDidChange:)
name:MPMoviePlayerPlaybackStateDidChangeNotification
object:player];
}
/* Notification called when the movie finished playing. */
- (void) moviePlayBackDidFinish:(NSNotification*)notification
{
NSNumber *reason = [[notification userInfo] objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
switch ([reason integerValue])
{
/* The end of the movie was reached. */
case MPMovieFinishReasonPlaybackEnded:
/*
Add your code here to handle MPMovieFinishReasonPlaybackEnded.
*/
break;
/* An error was encountered during playback. */
case MPMovieFinishReasonPlaybackError:
NSLog(#"An error was encountered during playback");
[self performSelectorOnMainThread:#selector(displayError:) withObject:[[notification userInfo] objectForKey:#"error"] waitUntilDone:NO];
[self removeMovieViewFromViewHierarchy];
break;
/* The user stopped playback. */
case MPMovieFinishReasonUserExited:
[self removeMovieViewFromViewHierarchy];
break;
default:
break;
}
}
/* Remove the movie view from the view hierarchy. */
-(void)removeMovieViewFromViewHierarchy
{
MPMoviePlayerController *player = [self moviePlayerController];
[player.view removeFromSuperview];
}
- (void)animate {
isAnimationStarted = YES;
//First Animation
[UIView animateWithDuration:0.5 animations:^{
dot1.alpha = 1;
dot2.alpha = 0.5;
dot3.alpha = 0.5;
} completion:^(BOOL finished) {
//2nd Animation
[UIView animateWithDuration:0.5 animations:^{
dot1.alpha = 0.5;
dot2.alpha = 1;
dot3.alpha = 0.5;
} completion:^(BOOL finished) {
//3rd Animation
[UIView animateWithDuration:0.5 animations:^{
dot1.alpha = 0.5;
dot2.alpha = 0.5;
dot3.alpha = 1;
} completion:^(BOOL finished) {
[self performSelector:#selector(animate)];
}];
}];
}];
}
// Find a camera with the specificed AVCaptureDevicePosition, returning nil if one is not found
- (AVCaptureDevice *) cameraWithPosition:(AVCaptureDevicePosition) position
{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *device in devices) {
if ([device position] == position) {
return device;
}
}
return nil;
}
// Find a front facing camera, returning nil if one is not found
- (AVCaptureDevice *) frontFacingCamera
{
return [self cameraWithPosition:AVCaptureDevicePositionFront];
}
// Find a back facing camera, returning nil if one is not found
- (AVCaptureDevice *) backFacingCamera
{
return [self cameraWithPosition:AVCaptureDevicePositionBack];
}
- (AVCaptureDevice *) audioDevice
{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
if ([devices count] > 0) {
return [devices objectAtIndex:0];
}
return nil;
}
-(void)audioData:(id)info
{
NSArray *connections = audioOutput.connections;
AVCaptureConnection *connection = [connections objectAtIndex:0];
NSArray *audioChannels = connection.audioChannels;
AVCaptureAudioChannel *audioChannel = [audioChannels objectAtIndex:0];
//[label setText:[NSString stringWithFormat:#"%f", audioChannel.averagePowerLevel]];
}
Guy's Please help me how to resolve this issue :(
Regards

Trying to fade in images loaded from URL asynchronously in XCode

I want to load images from a URL and then assign them as background images for different UIButtons. I need to do this when a view appears.
My problem is that when I try to make the images fade in when they are loaded, the animation does not start until all of the images have loaded. I think this is because the animation code is read but that before it has time to be executed, the program starts loading a new image.
How can I make images fade in one after the other?
The following code is used to get the image (calling downloadImageByPrice atURL) and then does the animation.
-(void) obtainImage:(int)i atURL:(NSString *)URLString{
UIImage *image = [self downloadImageByPrice:i atURL:URLString];
// Make images fade in when they have been found
[[_buttonArray objectAtIndex:i] setAlpha:0.0];
[[_buttonArray objectAtIndex:i] setImage:image forState:UIControlStateNormal];
[UIView beginAnimations:#"fadeIn" context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:0.8];
[[_buttonArray objectAtIndex:i] setAlpha:1.0];
[UIView commitAnimations];
}
This method is used to load all the images one after the other. I want my loop to wait until each image has appeared before starting to load the next one.
-(void) loadAllImagesAtURL:(NSString *)URLString{
for(int i =0; i<[_buttonArray count];i++){
[self obtainImage:i atURL:URLString];
}
}
I have tried using selectors, or the completion^ method with no luck, but my understanding of those concepts is still pretty low.
Thank you
Check this out:
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (strong, nonatomic) NSMutableArray *buttonArray;
-(void) loadAllImagesAtURL:(NSString *)URLString;
- (UIImage *)downloadImageAtURL:(NSString *)urlString;
#end
ViewController.m
#import "ViewController.h"
#implementation ViewController
#synthesize buttonArray = _buttonArray;
- (void)viewDidLoad {
[super viewDidLoad];
[self setButtonArray:[NSMutableArray array]];
int margin = 20;
int buffer = 8;
int width = 100;
int height = 50;
for (int i = 0; i < 4; i = i + 1) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setAlpha:0.0];
[btn setFrame:CGRectMake(margin + ((width + buffer) * i), margin, width, height)];
[btn setTitle:[NSString stringWithFormat:#"%d", i] forState:UIControlStateNormal];
[[self buttonArray] addObject:btn];
[[self view] addSubview:btn];
}
[self loadAllImagesAtURL:#"https://www.google.com/images/srpr/logo3w.png"];
}
-(void) loadAllImagesAtURL:(NSString *)URLString {
static int i = -1;
i = i + 1;
if (i < [[self buttonArray] count]) {
UIImage *image = [self downloadImageAtURL:URLString];
// Make images fade in when they have been found
[[_buttonArray objectAtIndex:i] setImage:image forState:UIControlStateNormal];
[UIView animateWithDuration:1.0
animations:^{
[[_buttonArray objectAtIndex:i] setAlpha:1.0];
}
completion:^(BOOL finished) {
[self loadAllImagesAtURL:URLString];
}
];
}
}
- (UIImage *)downloadImageAtURL:(NSString *)urlString {
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
return image;
}
#end
For me, this creates 4 buttons (that are initially invisible) that fade in when the image is downloaded. Is this what you want?

parsing json image

I'm parsing my data on this way:
NSDictionary *item = [tableData objectAtIndex:[indexPath row]];
[[cell textLabel] setText:[item objectForKey:#"title"]];
[[cell detailTextLabel] setText:[item objectForKey:#"description"]];
But is there a way to parse an cell image? Normally it's
UIImage *cellImage = [UIImage imageNamed:#"image.png"];
cell.imageView.image = cellImage;
But i'm searching for a way like
[[cell UIImage cellimage] ....
Something like that so i can parse an image url from json in it
is that possible?
NSURL *url = [NSURL URLWithString:[item objectForKey:#"image"]];
NSData *data = [NSData dataWithContentsOfURL:url];
cell.imageView.image = [UIImage imageWithData:data];
Set a max width for the image
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar // called when keyboard search button pressed
{
[spinner startAnimating];
spinner.hidden=NO;
NSLog( #" Searchbar text = %#",searchBar.text);
strSearch=searchBar.text;
strSearch=[strSearch stringByReplacingOccurrencesOfString:#" " withString:#"+"];
[searchBar resignFirstResponder];
[self searchGooglePhotos];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar // called when cancel button pressed
{
[searchBar resignFirstResponder];
}
-(void)searchGooglePhotos
{
// Build the string to call the Flickr API
NSString *urlString = [NSString stringWithFormat:#"http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=%#",strSearch];
NSLog(#"urlarrystring is := %#",urlString);
// Create NSURL string from formatted string
NSURL *url = [NSURL URLWithString:urlString];
// Setup and start async download
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection release];
[request release];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Store incoming data into a string
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// Create a dictionary from the JSON string
NSDictionary *respone = [jsonString JSONValue];
//NSLog(#"result dict is :%#",respone);
// Build an array from the dictionary for easy access to each entry
urlarry = [[[respone valueForKey:#"responseData"] valueForKey:#"results"]valueForKey:#"url"];
NSArray *title = [[[respone valueForKey:#"responseData"] valueForKey:#"results"]valueForKey:#"title"];
MoreUrlarry=[[[respone valueForKey:#"responseData"] valueForKey:#"cursor"]valueForKey:#"moreResultsUrl"];
[urlarry retain];
NSLog(#"photourlarry is :%#",urlarry);
NSLog(#"phototitle is :%#",title);
NSLog(#"photoMoreUrlarry is :%#",MoreUrlarry);
NSData *data2;
NSString *str=[[NSString alloc] init];
[scrl removeFromSuperview];
[displayview removeFromSuperview];
scrl=[[UIScrollView alloc] initWithFrame:CGRectMake(0, 44,320, 430)];
[scrl setContentSize:CGSizeMake(320*[urlarry count], 430)];
scrl.pagingEnabled=YES;
//==========
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Assign activity indicator to the pre-defined property (so it can be removed when image loaded)
//self.activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(55, 67, 25, 25)];
// Start it animating and add it to the view
// Create multiple imageviews to simulate a 'real' application with multiple images
CGFloat verticalPosition = 10;
int i = 1;
for (i=1; i<5; i++) {
// Set vertical position of image in view.
if (i > 1) {
verticalPosition = verticalPosition+85;
}
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(122, verticalPosition, 80, 80)];
imageView.tag = i;
[self.view addSubview:imageView];
// set the image to be loaded (using the same one here but could/would be different)
NSString *str123=[urlarry objectAtIndex:i-1];
NSURL *imgURL = [NSURL URLWithString:str123];
// Create an array with the URL and imageView tag to
// reference the correct imageView in background thread.
NSMutableArray *arr = [[NSArray alloc] initWithObjects:imgURL, [NSString stringWithFormat:#"%d", i], nil ];
// Start a background thread by calling method to load the image
[self performSelectorInBackground:#selector(loadImageInBackground:) withObject:arr];
}
[pool release];
/*
int x=10,y=50,p=250,q=20;
for (int i=0; i<[urlarry count]; i++)
{
str=[NSString stringWithString:[urlarry objectAtIndex:i]];
data2 = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
Favimage = [[UIImage alloc]initWithData:data2];
markButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[markButton setFrame:CGRectMake(p, q, 35,20)];
markButton.tag=i;
NSLog(#"tag is :%d",markButton.tag);
//[imgButton setTitle:[NSString stringWithFormat:#"%i",i] forState:UIControlStateNormal];
//imgButton.contentMode=UIViewContentModeScaleAspectFit;
// [imgButton setBackgroundImage:[UIImage imageNamed:#"no.png"]forState:UIControlStateNormal];
//[imgButton setImage:[Favimage imageScaledToFitSize:CGSizeMake(300, 320)] forState:UIControlStateNormal];
[markButton addTarget:self action:#selector(mark_buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[scrl addSubview:markButton];
UIButton *imgButton = [UIButton buttonWithType:UIButtonTypeCustom];
[imgButton setFrame:CGRectMake(x, y, 300,320)];
imgButton.tag=i;
NSLog(#"tag is :%d",imgButton.tag);
//[imgButton setTitle:[NSString stringWithFormat:#"%i",i] forState:UIControlStateNormal];
imgButton.contentMode=UIViewContentModeScaleAspectFit;
// [imgButton setBackgroundImage:[UIImage imageNamed:#"no.png"]forState:UIControlStateNormal];
[imgButton setImage:[Favimage imageScaledToFitSize:CGSizeMake(300, 320)] forState:UIControlStateNormal];
[imgButton addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
//[imgButton setImage:Favimage forState:UIControlStateNormal];
[scrl addSubview:imgButton];
//UIImageView *imageview=[[UIImageView alloc] initWithFrame:CGRectMake(x, y, 90, 90)];
// [imageview setImage:Favimage];
// [scrl addSubview:imageview];
NSLog(#"value of x=%d",x);
NSLog(#"value of y=%d",y);
NSLog(#"value of p=%d",p);
NSLog(#"value of q=%d",q);
NSLog(#"str is : %#",str);
if (y>=30 )
{
//x=15;
x=x+320;
}
if (q>=0 )
{
//x=15;
p=p+320;
}
//else
// {
// y=y+;
// }
}*/
[spinner stopAnimating];
spinner.hidden=TRUE;
[self.view addSubview:scrl];
btnmore.hidden=NO;
//NSLog(#"str is : %#",str);
// NSLog(#"j is : %d",j);
// NSLog(#"p is : %d",p);
}
- (void) loadImageInBackground:(NSArray *)urlAndTagReference {
NSLog(#"Received URL for tagID: %#", urlAndTagReference);
// Create a pool
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Retrieve the remote image. Retrieve the imgURL from the passed in array
NSData *imgData = [NSData dataWithContentsOfURL:[urlAndTagReference objectAtIndex:0]];
UIImage *img = [[UIImage alloc] initWithData:imgData];
// Create an array with the URL and imageView tag to
// reference the correct imageView in background thread.
NSMutableArray *arr = [[NSArray alloc] initWithObjects:img, [urlAndTagReference objectAtIndex:1], nil ];
// Image retrieved, call main thread method to update image, passing it the downloaded UIImage
[self performSelectorOnMainThread:#selector(assignImageToImageView:) withObject:arr waitUntilDone:YES];
}
- (void) assignImageToImageView:(NSArray *)imgAndTagReference
{
// Create a pool
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// loop
for (UIImageView *checkView in [self.view subviews] ) {
NSLog(#"Checking tag: %d against passed in tag %d",[checkView tag], [[imgAndTagReference objectAtIndex:1] intValue]);
if ([checkView tag] == [[imgAndTagReference objectAtIndex:1] intValue]) {
// Found imageView from tag, update with img
[checkView setImage:[imgAndTagReference objectAtIndex:0]];
//set contentMode to scale aspect to fit
checkView.contentMode = UIViewContentModeScaleAspectFit;
//change width of frame
CGRect frame = checkView.frame;
frame.size.width = 80;
checkView.frame = frame;
}
}
// release the pool
[pool release];
// Remove the activity indicator created in ViewDidLoad()
//[self.activityIndicator removeFromSuperview];
}
-(void)buttonPressed:(id)sender
{
UIButton *imgButton = (UIButton *)sender;
int q=imgButton.tag;
string=[[NSString alloc] init];
string=[NSString stringWithString:[urlarry objectAtIndex:q]];
// NSLog(#"aap str is :%#",appDel.appstr);
// [self.navigationController pushViewController:objimv animated:YES];
}

How to set the thumbnail image got from MpMoviePlayerController as a thumbnail when loading the video url string into webview?

I got the thumbnail Image by passing the video url to the MPMoviePlayerController and I am playing the video by loading the Url string into the webview How can I set the Thumbnailimage as a thumnailwhen playing the video in webview at present I am getting white screen with play button.
My code is:
MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:newURL];
if (moviePlayer)
{
[moviePlayer setControlStyle:MPMovieControlStyleFullscreen];
[moviePlayer setFullscreen:YES];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(handleDurationAvailableNotification:)
name:MPMovieDurationAvailableNotification
object:moviePlayer];
moviePlayer.useApplicationAudioSession = NO;
UIImage *image = [moviePlayer thumbnailImageAtTime:(NSTimeInterval)1.0 timeOption: MPMovieTimeOptionNearestKeyFrame];
NSData *imgData = UIImagePNGRepresentation(image);
printf("\n length of ThumbnailImage Data...%d",[imgData length]);
// May help to reduce latency
//[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(movieFinishedCallback:) name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayer];
///moviePlayer.view.frame = CGRectMake(184, 200, 400, 300);
//[self.view addSubview:moviePlayer.view];
//[moviePlayer play];
}
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
printf("\n Inside didSelect method....!!");
masterAisleItemListIndexArray = (NSMutableArray*)[ [masterAisleItemListDictionary allKeys] sortedArrayUsingSelector:#selector(compare:)];
NSString* sectionName = [masterAisleItemListIndexArray objectAtIndex:indexPath.section];
NSMutableArray* aisleItemsArray = [masterAisleItemListDictionary valueForKey:sectionName];
CustomerDetails *custObj = [aisleItemsArray objectAtIndex:indexPath.row];
//CustomerDetails *custObj = [videosList objectAtIndex:indexPath.row];
printf("\n audiofile = %s",[custObj.audioFile UTF8String]);
//NSURL *URL = [NSURL URLWithString:custObj.audioFile];
//printf("URL====%s",[URL UTF8String]);
webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, 440)];
[myView addSubview:webView];
webView.backgroundColor = [UIColor blueColor];
[webView loadHTMLString:[self getVideo:custObj.audioFile] baseURL:[NSURL URLWithString:#"http:bluepal.com"]];
webView.delegate = self;
self.view = myView;
//[self downloadOutstandingFileSounds:custObj.audioFile];
}
-(NSString *)getVideo:(NSString *)aString
{
NSString *htmlString = #"<html><head><meta name = \"viewport\" content = \"initial-scale = 1.0, user-scalable = no, width = 94\"/></head><body style=\"background:#000;margin-top:0px;margin-left:0px\"><div><object width=\"90\" height=\"70\"><embed src=\"";
htmlString = [htmlString stringByAppendingString:aString];
htmlString = [htmlString stringByAppendingString:#"\"type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"320\" height=\"400\"></embed></object></div></body></html>"];
printf("\n htmlString.......%s",[htmlString UTF8String]);
return htmlString;
}
Guys please give me suggestions to get out of this.
Hope I wil get quick response from your side.
Thanks all,
Lakshmi.