I am making a program that loads videos from a server and then saves them locally. The programmed worked fine when i was doing it synchronizely. When I changed it to do it asynchronously , it would crash when the person return to the pre screen and try to press any of the buttons with a sig bad memory error.
What happens is the vedio loads and plays ok. When they click the done button the methed
- (void) moviePlayBackDidFinish:(NSNotification*)notification;{
[ mp stop];
// [ mp release];
[self dismissModalViewControllerAnimated: true];
}
exicutes and it goes to the pre screen. Now on the pre screen, if they click on any button, i get a
I did the following
1. the file is big so I chnage my
[[NSMutableData alloc] initWithLebngth:0]; to [[NSMutableData alloc] initWithCapacity:200000];, did not work.
- (void)viewDidLoad {
[super viewDidLoad];
// construct the url
NSString *mServerName=[ [ NSString alloc] initWithString:#"http://www.besttechsolutions.biz/projects/golfflix/" ];
NSString *mFullName=[ mServerName stringByAppendingString: mVedioName ];
NSURL *movieUrl=[[NSURL alloc] initWithString:mFullName];
// start the transmision
NSURLRequest *theRequest = [NSURLRequest requestWithURL:movieUrl cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
receivedData = [[NSMutableData alloc] initWithCapacity:100000000];
connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
[movieUrl release];
[mServerName release];
}
///////////////////////////////////////////////////////////////////////////////////////////////
// background loading
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[receivedData setLength:0];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[connection release];
}
- (NSCachedURLResponse *) connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
return nil;
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[connection release];
/////////////////////////////////////////////////////////////////////////////////
// Save vedio
NSFileManager *mFile= [NSFileManager defaultManager];
NSString *filename=[ NSHomeDirectory() stringByAppendingPathComponent:mVedioName];
[mFile createFileAtPath:filename contents: receivedData attributes:nil];
[ receivedData release ];
// play it
NSURL *fileUrl=[ NSURL fileURLWithPath:filename];
if (mp==nil)
{
mp=[[MPMoviePlayerController alloc] initWithContentURL: fileUrl];
[mp.view setFrame: self.view.bounds];
[self.view addSubview: mp.view];
// Set movie player layout
[mp setControlStyle:MPMovieControlStyleFullscreen];
[mp setFullscreen:YES];
// May help to reduce latency
[mp prepareToPlay];
[mp play];
}
else {
[mp stop];
mp.contentURL=fileUrl;
[mp play];
}
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:nil];
// movie reced save to file
}
- (void) moviePlayBackDidFinish:(NSNotification*)notification;{
[ mp stop];
// [ mp release];
[self dismissModalViewControllerAnimated: true];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
any thoughts on this would be GREAT, ben stuck for days!!!!
Ted
If you are coming back to the pre screen then try to shift your code to
-(void)viewWillAppear:(BOOl)animated
{
//code
}
because the function viewDidLoad will be called only one time when the view is loaded.
but the function viewWillAppear will be called whenever that view will appear.
Related
This question already has answers here:
iPhone SDK: How do you download video files to the Document Directory and then play them?
(2 answers)
How to download audio/video files from internet and store in iPhone app?
(2 answers)
Closed 9 years ago.
I am downloading a video like this..
-(IBAction)buttonPress:(id)sender{
movieURL = [NSURL URLWithString:#"https://www.dropbox.com/s/Screen%20Capture2013-01-31%2014_21_22.mov"];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:movieURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
if( connection )
{
receivedData = [[NSMutableData alloc] initWithLength:0];
}
else
{
//[delegate ConnectionFailed];
}
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[receivedData setLength:0];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
NSLog(#"dee- %#",receivedData);
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
// [connection release];
}
- (NSCachedURLResponse *) connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
return nil;
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
// [connection release];
[self movieReceived];
}
But I am not able to play this video. Please help me to save and play this video.
i have tried this but doesnt work.\
-(void)movieReceived{
MPMoviePlayerViewController* tmpMoviePlayViewController=[[MPMoviePlayerViewController alloc] initWithContentURL:movieURL];
if (tmpMoviePlayViewController) {
tmpMoviePlayViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentViewController:tmpMoviePlayViewController animated:YES completion:nil];
tmpMoviePlayViewController.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(myMovieViewFinishedCallback:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:tmpMoviePlayViewController];
[tmpMoviePlayViewController.moviePlayer play];
}
}
use below code
-(void)movieReceived{
{
NSString *strVideoUrl = #"abc.com/xyz" // your VideoUrl in String
strVideoUrl = [strVideoUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:strVideoUrl];
moviePlayer=[[MPMoviePlayerController alloc] initWithContentURL:url];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(moviePlayBackDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayer];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(moviePlayBackDonePressed:) name:MPMoviePlayerDidExitFullscreenNotification object:moviePlayer];
moviePlayer.controlStyle=MPMovieControlStyleDefault;
//moviePlayer.shouldAutoplay=NO;
[moviePlayer play];
[self.view addSubview:moviePlayer.view];
[moviePlayer setFullscreen:YES animated:YES];
}
- (void) moviePlayBackDonePressed:(NSNotification*)notification
{
[moviePlayer stop];
[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerDidExitFullscreenNotification object:moviePlayer];
if ([moviePlayer respondsToSelector:#selector(setFullscreen:animated:)])
{
[moviePlayer.view removeFromSuperview];
}
moviePlayer=nil;
}
- (void) moviePlayBackDidFinish:(NSNotification*)notification
{
[moviePlayer stop];
[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayer];
if ([moviePlayer respondsToSelector:#selector(setFullscreen:animated:)])
{
[moviePlayer.view removeFromSuperview];
}
}
use like this your problem will solve ~~~~~Best Of Luck ~~~~~~
I want to create two connections in a single view controller class. I am using NSOperationQueue for this purpose. The two connections are created in two functions and push inside the queue .The problem is delegates are not called. Please help me out. Thanks you in advance
- (void)viewDidLoad {
[super viewDidLoad];
NSOperationQueue *queue=[[NSOperationQueue alloc] init];
NSInvocationOperation *invOperation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:#selector(createConnection1) object:nil];
NSInvocationOperation *invOperation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:#selector(createConnection2) object:nil];
NSArray *ops=[[NSArray alloc] initWithObjects:invOperation1,invOperation2,nil];
[queue addOperations:ops waitUntilFinished:YES];
}
-(void) createConnection1{
//create connection
NSLog(#"Create Connection 1");
url1 =[[NSMutableString alloc] initWithFormat:#"http://www.google.com/ig/api?weather=New Delhi"];
NSURLRequest *theRequest1=[NSURLRequest requestWithURL:[NSURL URLWithString:url1]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
theConnection1=[[NSURLConnection alloc] initWithRequest:theRequest1 delegate:self];
if (theConnection1) {
connectionCreated1=YES;
receivedData1 = [[NSMutableData data] retain];
NSLog(#"received data 1 %#",receivedData1);
//[theConnection1 setDelegate:self];
}
}
-(void) createConnection2{
//create connection
NSLog(#"Create Connection 2");
url2 =[[NSMutableString alloc] initWithFormat:#"http://www.google.com/ig/api?weather=Chennai"];
NSURLRequest *theRequest2=[NSURLRequest requestWithURL:[NSURL URLWithString:url2]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
theConnection2=[[NSURLConnection alloc] initWithRequest:theRequest2 delegate:self];
if (theConnection2) {
connectionCreated2=YES;
receivedData2 = [[NSMutableData data] retain];
//[theConnection2 setDelegate:self];
NSLog(#"received data 2 %#",receivedData2);
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
if (connectionCreated1==YES) {
[receivedData1 setLength:0];
}
else if (connectionCreated2==YES) {
[receivedData2 setLength:0];
}
else {
NSLog(#"did not receive response");
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
if (connectionCreated1==YES) {
[theConnection1 release];
xmlParser1 = [[NSXMLParser alloc] initWithData:receivedData1];
[xmlParser1 setDelegate:self];
[xmlParser1 parse];
}
else if(connectionCreated2==YES){
[theConnection2 release];
xmlParser2 = [[NSXMLParser alloc] initWithData:receivedData2];
[xmlParser2 setDelegate:self];
[xmlParser2 parse];
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"connection failed" message:#"" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if (connectionCreated1==YES) {
[receivedData1 appendData:data];
}
else if(connectionCreated2==YES) {
[receivedData2 appendData:data];
}
else {
NSLog(#"data not received");
}
}
The URL you have given in the first link seems to be borken ... look at this "http://www.google.com/ig/api?weather=New Delhi".. there is space between new delhi. try this instead http://www.google.com/ig/api?weather=New+Delhi
"Informazioni.h file"
#interface Informazioni : UIViewController{
.....
ASIHTTRequest *mASIHTTPRequest;
}
#property (nonatomic, retain) ASIHTTRequest *mASIHTTPRequest;
----------------------------
#import "Informazioni.h"
#import "Globals.h"
#implementation Informazioni
#synthesize mImageViewImmagine;
....
#synthesize mASIHTTPRequest;
- (void)viewDidLoad {
[super viewDidLoad];
//start fetching based on id_prodotti
[self startFetch:mId_prodotto];
}
- (void) startFetch:(NSString *) pId_prodotto{
//activate ASIHTTPDownloadCache
NSURL *url = [NSURL URLWithString:[JSON_DESCRIZIONE stringByAppendingString:mId_prodotto]];//JSON_DATA
mASIHTTPRequest = [ASIHTTPRequest requestWithURL:url];
[mASIHTTPRequest setDelegate:self];
[mASIHTTPRequest startAsynchronous];
}
- (void)loadDataWithOperation: (NSString *) responseString{
NSLog(#"load data with operation");
NSDictionary *tempDict = [[responseString JSONValue] objectForKey:#"descrizione_prodotto"];
NSLog(#"descrizione_prodotto: %#",tempDict);
[self.mTableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:YES];
NSLog(#"reloadData called");
}
//start
- (void)requestFinished:(ASIHTTPRequest *)request{
NSLog(#"SUCCESS Http fetching");
// Operation Queue init (autorelease)
NSOperationQueue *queue = [NSOperationQueue new];
// Create our NSInvocationOperation to call loadDataWithOperation, passing in nil
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
selector:#selector(loadDataWithOperation:)
object:[request responseString]];
// Add the operation to the queue
[queue addOperation:operation];
[operation release];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
NSLog(#"%#",[error localizedDescription]);
/*
NSLog(#"Error: %#",[error localizedDescription]);
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"DIUNAMAISHOP"
message:[error localizedDescription]
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
*/
/*
//remove activity indicator
if (self.mActivityIndicator.mFlag == YES) {
[self.mActivityIndicator.view
performSelectorOnMainThread:#selector(removeFromSuperview)
withObject:nil waitUntilDone:YES];
}
*/
}
-(void) queueFinished:(ASIHTTPRequest *) queue{
//You could release the queue here if you wanted
NSLog(#"Queue finished");
}
// end
........
- (void)dealloc {
//safely dealllocate
[mASIHTTPRequest clearDelegatesAndCancel];
[mASIHTTPRequest release];
.....
[super dealloc];
NSLog(#"Informazioni deallocated");
}
#end
I simply pushed this view then pressing back will dealloc/release the viewcontroller..
- the problem is it crashes when i press back while it is fetching
- how can i overcome this any suggestion would do tnx
mASIHTTPRequest = [ASIHTTPRequest requestWithURL:url];
You're not retaining this request. You need to retain it to have a valid reference reference to then be able to cancel and release it. Either add a retain, or use self.mASIHTTPRequest.
I am created an application which play multiple audio files from locally. Audio files are long. Audio player has following options for the user
Forward,
Rewind,
Next Track,
Previous Track,
I am planning to use AvAudioPlayer so that i can play an audio with long time. When i am changing the audio file ie pressing next track audio. The audioplayer instance is not getting released. This problem is appearing some times only. Please help me..!! I am help less..
Next Track Button IBAction Method
- (IBAction) nextTrackPressed
{
[audioPlay stopAudio];
if (audioPlay) {
audioPlay = nil;
[audioPlay release];
}
appDelegate.trackSelected += 1;
[self intiNewAudioFile];
[self play];
}
Initializing audio file through below method
-(void) intiNewAudioFile
{
NSAutoreleasePool *subPool = [[NSAutoreleasePool alloc] init];
NSString *filePath = [[NSString alloc] init];
trackObject = [appDelegate.trackDetailArray objectAtIndex:appDelegate.trackSelected];
NSLog(#"%#",trackObject.trackName);
// Get the file path to the song to play.
filePath = [[NSBundle mainBundle] pathForResource:trackObject.trackName ofType:#"mp3"];
// Convert the file path to a URL.
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
if (audioPlay) {
audioPlay = nil;
[audioPlay release];
}
audioPlay = [[AudioPlayerClass alloc] init];
[audioPlay initAudioWithUrl:fileURL];
[filePath release];
[fileURL release];
[subPool release];
}
AudioPlayerClass Implementation
#import "AudioPlayerClass.h"
#implementation AudioPlayerClass
- (void) initAudioWithUrl: (NSURL *) url
{
curAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[curAudioPlayer setDelegate:self];
[curAudioPlayer prepareToPlay];
}
- (void) playAudio
{
[curAudioPlayer play];
}
- (void) pauseAudio
{
[curAudioPlayer pause];
}
- (void) stopAudio
{
[curAudioPlayer stop];
}
- (BOOL) isAudioPlaying
{
return curAudioPlayer.playing;
}
- (void) setAudiowithCurrentTime:(NSInteger) time
{
curAudioPlayer.currentTime = time;
}
- (NSInteger) getAudioFileDuration
{
return curAudioPlayer.duration;
}
- (NSInteger) getAudioCurrentTime
{
return curAudioPlayer.currentTime;
}
- (void) releasePlayer
{
[curAudioPlayer release];
}
- (void)dealloc {
[curAudioPlayer release];
[super dealloc];
}
#end
Your problem is here:
if (audioPlay) {
audioPlay = nil;
[audioPlay release];
}
You are setting audioPlay to nil before calling release which means that the release message is getting sent to nil. You need to reverse the order of these 2 lines.
if (audioPlay) {
[audioPlay release];
audioPlay = nil;
}
In my app I am using UIwebview to display websites, however whenever I click back button and start playing with other parts in the app, the app mostly crashes with no reason. I suspect the webview is causing this issue because it crashes only when I try to open the webview.
I have used NSURLConnection to load the webview and have made webview, connection objects to nil in the view will Disappear method.
#implementation NewsWebSiteViewController
#synthesize connection,rcvdData,spinner1,currentSite,webView,newsWebsite;
- (void)viewDidLoad {
[super viewDidLoad];
#try {
self.webView.delegate=self;
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
self.title= self.newsWebsite.title;
self.webView.backgroundColor =[UIColor groupTableViewBackgroundColor];
self.spinner1 = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
CGRect center = [self.view bounds];
CGSize winCenter = center.size;
CGPoint pont = CGPointMake(winCenter.width/2,winCenter.height/2);
[spinner1 setCenter:pont];
[self.view addSubview:spinner1];
[self.spinner1 startAnimating];
NSString *url = newsWebsite.link;
NSURLRequest *theReq =[NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
self.connection = [[NSURLConnection alloc] initWithRequest:theReq delegate:self];
if(self.connection) {
self.rcvdData = [[NSMutableData data] retain];
}
else {
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Error!" message:#"We are having a problem connecting to the internet, why not try again or try sometime later!.." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil] autorelease];
[alert show];
}
webView.multipleTouchEnabled=YES;
webView.scalesPageToFit=YES;
}
#catch (NSException * e) {
}
}
-(void) goBack {
self.webView =nil;
[self.navigationController popViewControllerAnimated:YES];
}
-(void) viewWillDisappear:(BOOL)animated {
[self.connection cancel];
self.connection=nil;
[self.webView stopLoading];
self.webView=nil;
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
if (self.spinner1 ==nil) {
}
else {
[self.spinner1 stopAnimating];
}
}
-(void) webViewDidFinishLoad:(UIWebView *)webView {
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
if (self.spinner1 ==nil) {
}
else {
[self.spinner1 stopAnimating];
}
}
-(void) viewDidAppear:(BOOL)animated {
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self.rcvdData setLength:0];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.rcvdData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
if (self.spinner1 ==nil) {
}
else {
[self.spinner1 stopAnimating];
}
[connection release];
[rcvdData release];
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Error!" message:#"We are having a problem connecting to the internet, why not try again or try sometime later!.." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil] autorelease];
[alert show];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
[rcvdData release];
NSString *url = newsWebsite.link;
NSURL *url1 = [NSURL URLWithString:url];
[self.webView loadData:self.rcvdData MIMEType:#"text/html" textEncodingName:#"UTF-8" baseURL:url1];
}
- (void)dealloc {
[super dealloc];
[self.spinner1 release];
}
#end
Firstly, here's a small primer to equality/inequality in C/Objective-C:
Let's say you have a BOOL value (ie, a value that can be either YES or NO, 'On' or 'Off', 'True' or 'False'), called isEnabled. Now, if I had assigned this BOOL value (sometimes called a 'flag') to 'YES', I could conditionally test its value like so:
BOOL isEnabled = YES;
if (isEnabled)
{
// value set to yes
}
In addition to the above, I can use the negation operator (an exclamation mark - otherwise known as the NOT operator) to flip isEnabled's value, and test its opposite value:
BOOL isEnabled = YES;
// the following reads as "if is *not* enabled"
if (!isEnabled)
{
// value set to no
}
now of course in the above example isEnabled is set to YES, so the condition will fail. But, if we consider the following example, the property of if whereby if an else if is 'met' (ie, true) anywhere in a series of if's and else if's, it will execute all the code inside it, and then ignore anything else:
BOOL isEnabled = NO;
if (isEnabled)
{
// any code here will not run, as the above if condition will be false
}
else if (!isEnabled)
{
// this code will run, since the above condition (!isEnabled) will evaluate to true
}
else if (isEnabled)
{
// this code could never run, since the previous condition was true and all following else if's are ignored
}
else if (!isEnabled)
{
// this code could never run, since the previous condition was true and all following else if's are ignored
}
while the above has two redundant else if's at the end, it is a good way to demonstrate how conditional code works.
So, in your webViewDidFinishLoad: method, instead of having a blank if to evaluate an if/else condition, you can replace that with a simpler condition:
-(void) webViewDidFinishLoad:(UIWebView *)webView
{
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
// or, (self.spinner1 != nil)
if (!self.spinner1)
{
[self.spinner1 stopAnimating];
}
}
When you've made the above change to all your if's and else if's, post a stack trace and I'll see what else it could be.