UIWebView: Delegate won't be called - objective-c

I try to calculate the size of a UIWebView with a given content, but without showing the view. I only need to know the size.
My Problem: When I execute the code, the delegate of the UIWebView isn't called. Why?
MessageSizeCaluclator.h
#import < Foundation/Foundation.h>
#class Message;
#interface MessageSizeCaluclator : NSObject <UIWebViewDelegate>
- (id)initWithMessage:(Message*)message;
- (void)saveSize;
#end
MessageSizeCaluclator.m
#import "Message.h"
#import "MessageSizeCaluclator.h"
#interface MessageSizeCaluclator () <UIWebViewDelegate>
#property (strong, nonatomic) Message* message;
#property (strong, nonatomic) UIWebView* webView;
#end
#implementation MessageSizeCaluclator
#synthesize message = _message;
#synthesize webView = _webView;
- (id)initWithMessage:(Message*)message
{
self = [super init];
if (self) {
_message = message;
// WebView
_webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
_webView.delegate = self;
}
return self;
}
- (void)saveSize
{
NSLog(#"%s message = %#", __PRETTY_FUNCTION__, _message.text);
[_webView loadHTMLString:[NSString stringWithFormat:#"<div style='font-family:Helvetica;font-size:13px;'>This is a test</div>", _message.text]
baseURL:nil];
}
#pragma mark - Web view delegate
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
NSLog(#"%s", __PRETTY_FUNCTION__);
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
NSLog(#"%s", __PRETTY_FUNCTION__);
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSLog(#"%s", __PRETTY_FUNCTION__);
}
#end
Implementation
MessageSizeCaluclator* messageSizeCalculator = [[MessageSizeCaluclator alloc] initWithMessage:message];
[messageSizeCalculator saveSize];

Add your UIWebView to some UIView, make its frame offscreen (so users can't see it). The delegate methods won't be called if UIWebView is not in the view hierarchy of the app.

Related

I am not able to get Navigation Bar using JSQMessagesViewController

Problem in getting Navigation Bar using JSQMessagesViewController, I have tried getting Navigation Bar in my project, but failed to get it. Please let me know what the methods need to be added to get it.
#import "JSQMessagesCollectionViewFlowLayout.h"
#import "JSQMessages.h"
#import "JSQPhotoMediaItem.h"
#import "JSQLocationMediaItem.h"
#import "JSQVideoMediaItem.h"
#import "JSQMessagesMediaViewBubbleImageMasker.h"
#import "JSQMessagesAvatarImage.h"
#import "JSQMessagesAvatarImageFactory.h"
#import "JSQMessagesBubbleImage.h"
#import "JSQMessagesBubbleImageFactory.h"
#import "UIImage+JSQMessages.h"
#import "Chat.h"
#interface ChatpageViewController : JSQMessagesViewController
{
NSMutableArray * fularray;
}
#property(nonatomic,strong)NSDictionary * receivedict;
#property (strong, nonatomic) IBOutlet UILabel *name;
#property (strong, nonatomic) IBOutlet UILabel *mobile;
#property (strong, nonatomic) JSQMessagesBubbleImage *outgoingBubbleImageData;
#property (strong, nonatomic) JSQMessagesBubbleImage *incomingBubbleImageData;
#end
#import "ChatpageViewController.h"
#interface ChatpageViewController ()
#end
#implementation ChatpageViewController
#synthesize receivedict,name,mobile;
//-(void)viewWillAppear:(BOOL)animated
//{
//
// // self.collectionView.collectionViewLayout.springinessEnabled = YES;
//}
(void)viewDidLoad
{
[super viewDidLoad];
fularray = [[NSMutableArray alloc] init];
// Do any additional setup after loading the view.
// [self.navigationController setNavigationBarHidden:NO animated:YES];
NSLog(#"%#",receivedict);
name.text = [receivedict objectForKey:#"Name"];
mobile.text =[receivedict objectForKey:#"Mobile"];
JSQMessagesBubbleImageFactory *bubbleFactory = [[JSQMessagesBubbleImageFactory alloc] init];
self.outgoingBubbleImageData = [bubbleFactory outgoingMessagesBubbleImageWithColor:[UIColor jsq_messageBubbleBlueColor]];
self.incomingBubbleImageData = [bubbleFactory incomingMessagesBubbleImageWithColor:[UIColor jsq_messageBubbleLightGrayColor]];
}
(id)collectionView:(JSQMessagesCollectionView *)collectionView messageBubbleImageDataForItemAtIndexPath:(NSIndexPath *)indexPath
{
JSQMessage *message = [fularray objectAtIndex:indexPath.item];
if ([message.senderId isEqualToString:self.senderId]) {
return self.outgoingBubbleImageData;
}
return self.incomingBubbleImageData;
}
(id)collectionView:(JSQMessagesCollectionView *)collectionView avatarImageDataForItemAtIndexPath:(NSIndexPath *)indexPath {
return [JSQMessagesAvatarImageFactory avatarImageWithUserInitials:#"JL" backgroundColor:[UIColor blueColor] textColor:[UIColor whiteColor] font:[UIFont systemFontOfSize:12.0] diameter:30.0];
}
(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [fularray count];
}
(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
(id)collectionView:(JSQMessagesCollectionView *)collectionView messageDataForItemAtIndexPath:(NSIndexPath *)indexPath {
return fularray[indexPath.row];
}
(void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
(NSString *)senderId
{
return [receivedict objectForKey:#"Mobile"];
}
(NSString *)senderDisplayName
{
return [receivedict objectForKey:#"Name"];
}
(NSDate *)date
{
return 18/03/2016;
}
(void)didPressSendButton:(UIButton *)button withMessageText:(NSString *)text senderId:(NSString *)senderId senderDisplayName:(NSString *)senderDisplayName date:(NSDate *)date
{
[JSQSystemSoundPlayer jsq_playMessageSentSound];
JSQMessage *message = [[JSQMessage alloc] initWithSenderId:senderId
senderDisplayName:senderDisplayName
date:date
text:text];
[fularray addObject:message];
[self.collectionView reloadData];
[self finishSendingMessageAnimated:YES];
NSLog(#"%#",message);
}
Myproject is saved in the link :https://www.dropbox.com/s/ozih8ko9836fmb2/chatapp.zip?dl=0
Goto MainStoryboard->select your Controller-> in menu choose Editor-> Embed in -> Navigation Controller
Change in JSQMessagesViewController.m file in -(void)jsq_updateCollectionViewInsets
[self jsq_setCollectionViewInsetsTopValue:self.topContentAdditionalInset + 64 bottomValue:CGRectGetMaxY(self.collectionView.frame) - CGRectGetMinY(self.inputToolbar.frame)];

Passing data in NSString format from LoginViewController to FirstViewController

LoginViewController is my initial view controller. Email address is an input in the LoginViewController and I am trying to send it to FirstViewController. I went through a lot of solutions posted here but was unsuccessful to find a link to my answer.
Please have a look at my code and tell me where I am going wrong. I am stuck at this point from a couple of days. My main problem is that, the output of emailString shows null when I print it to see if it was carried to the FirstViewController.
FYI - I am using storyboard. I have a Tab Bar Controller which has three tabs and FirstViewController is the first tab page.
LoginViewController.h
#import <UIKit/UIKit.h>
#import "FirstViewController.h"
#interface LoginViewController : UIViewController{
NSString *email;
}
- (IBAction)LoginButton:(id)sender;
- (IBAction)CancelButton:(id)sender;
- (IBAction)dismissKeyboard:(id)sender;
#property (weak, nonatomic) IBOutlet UITextField *EmailField;
#property (weak, nonatomic) IBOutlet UITextField *PasswordField;
#end
LoginViewController.m
#import "LoginViewController.h"
#import "FirstViewController.h"
#define USERNAME #"abc#gmail.com"
#interface LoginViewController ()
#end
#implementation LoginViewController
#synthesize EmailField;
#synthesize PasswordField;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
email = [[NSString alloc] init];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (IBAction)LoginButton:(id)sender {
email = EmailField.text;
if([EmailField.text isEqualToString:USERNAME])
{
FirstViewController *fvc = [[FirstViewController alloc]initWithNibName:#"FirstViewController" bundle:nil];
fvc.emailString = [[NSString alloc] initWithFormat:#"%#",EmailField.text];
// fvc.emailString = email;
[self.navigationController pushViewController:fvc animated:YES];
}
[EmailField resignFirstResponder];
}
- (IBAction)CancelButton:(id)sender {
NSLog(#"Cancel button pressed!!!");
[EmailField resignFirstResponder];
[PasswordField resignFirstResponder];
}
- (IBAction)dismissKeyboard:(id)sender {
[EmailField resignFirstResponder];
[PasswordField resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[self LoginButton:nil];
[textField resignFirstResponder];
return YES;
}
#end
FirstViewController.h
#import <UIKit/UIKit.h>
#import "LoginViewController.h"
#interface FirstViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *emailLabel;
#property (nonatomic, retain) NSMutableData *receivedData;
#property (copy) NSString *emailString;
FirstViewController.m
#import "FirstViewController.h"
#interface FirstViewController ()
#end
#implementation FirstViewController
#synthesize emailLabel;
#synthesize receivedData;
#synthesize emailString;
- (void)viewDidLoad
{
[super viewDidLoad];
[emailLabel setText: emailString];
NSString *theURL = [NSURL URLWithString:[NSString stringWithFormat:#"http://.....email=%#",emailString]];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:theURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if(connection){
NSLog(#"connection successful");
NSLog(#"%#",emailString);
receivedData = [NSMutableData data];
}
else{
NSLog(#"connection failed");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[receivedData setLength:0];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(#"Success");
NSLog(#"Received %d bytes of data",[receivedData length]);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#end
I tried implementing prepareFOrSegue method in LoginViewController too. But it still didnot make any change. This is the code I have written in it.
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([segue.identifier isEqualToString:#"showDetailSegue"])
{
NSString *email = EmailField.text;
NSLog (#"++++++++++ %#", email);
FirstViewController *fvc = [segue destinationViewController];
fvc.emailString=email;
}
}
Screenshot of Storyboard:
If you are using StoryBoards I'd strongly suggest you use segues to call the different view controllers. That way you can push vc's and pass info relatively easily.
You can override the native method prepareForSegue in your Login VC, and set the properties there. You can name your segue id as anything in the storyboard.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"firstVC"]) {
FirstViewController *firstVC = [segue destinationViewController];
firstVC.emailString = EmailField.text;
}
}
if you really want, and I'd advise against it vs. using static variables is
NSUserDefaults.
[[NSUserDefaults standardUserDefaults]
setObject:EmailField.text forKey:#"emailString"];
to get it back later
NSString *emailString = [[NSUserDefaults standardUserDefaults]
stringForKey:#"emailString"];
NSLog(#"%#",emailString);
I would save the Email and password in the IOS Keychain securely instead of passing it in between views.
https://developer.apple.com/library/ios/#documentation/security/conceptual/keychainServConcepts/iPhoneTasks/iPhoneTasks.html#//apple_ref/doc/uid/TP30000897-CH208-SW1
I got the solution.
The only three lines requires for me to add in the prepareForSegue were these three and I got my program working
FirstViewController* fvc = [[FirstViewController alloc] init];
UITabBarController *tbc = [segue destinationViewController];
fvc = (FirstViewController *) [[tbc customizableViewControllers] objectAtIndex:0];
Thanks everyone!

Call method from another view, I think?

I have a simple utility app, with a MainViewController.m & h and a FlipsideViewController.m & h. Within my storyboard I have a button on MainViewController. I want to be able to click the button and run a method in FlipsideViewController.m is this possible? this is my first app and I am a total novice. all comments / suggestion welcome.
enter code here
i have this in my FlipsideViewController.m this is what i want to call when i click the button.
- (void)SaveFPQData
{
NSLog(#"Data Saved");
}
and this is what i have in MainViewController.m
- (IBAction)saveButton:(id)sender
{
}
This is the code I have so far;
MainViewController.h
#import "FlipsideViewController.h"
#import "sqlite3.h"
#import "FPQCheck.h"
#interface MainViewController : UIViewController <FlipsideViewControllerDelegate>
#property (weak, nonatomic) IBOutlet UITextField *nameField;
#property (weak, nonatomic) IBOutlet UITextField *checkField;
#property (weak, nonatomic) IBOutlet UITextField *commentsField;
#property (weak, nonatomic) FlipsideViewController *flipsidecontroller;
- (IBAction)saveButton:(id)sender;
- (IBAction)showHistoryButton:(id)sender;
#end
MainViewController.m
#import "MainViewController.h"
#import "FlipsideViewController.h"
#import "sqlite3.h"
#interface MainViewController ()
#end
#implementation MainViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
// Do any additional setup after loading the view, typically from a nib.
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Flipside View
- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"showAlternate"]) {
[[segue destinationViewController] setDelegate:self];
}
}
- (IBAction)saveButton:(id)sender
{
[self.flipsidecontroller SaveFPQData];
//[[NSNotificationCenter defaultCenter] postNotificationName:#"SaveFPQData" object:nil];
}
- (IBAction)showHistoryButton:(id)sender
{
}
#end
FlipSideViewController.h
#import <UIKit/UIKit.h>
#import "FPQCheck.h"
#class FlipsideViewController;
#protocol FlipsideViewControllerDelegate
- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller;
#end
#interface FlipsideViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
#property (weak, nonatomic) IBOutlet UITableView *myTableView;
#property (weak, nonatomic) id <FlipsideViewControllerDelegate> delegate;
-(void)SaveFPQData;
- (IBAction)done:(id)sender;
- (IBAction)deleteEntry:(id)sender;
#end
FlipSideViewController.m
#import "FlipsideViewController.h"
#import "MainViewController.h"
#interface FlipsideViewController ()
{
NSMutableArray *arrayOfCheck;
sqlite3 *fpqDB;
NSString *dbPathString;
}
#end
#implementation FlipsideViewController
- (void)viewDidLoad
{
/*
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(SaveFPQData)
name:#"SaveFPQData"
object:nil];
*/
[super viewDidLoad];
arrayOfCheck = [[NSMutableArray alloc]init];
[self creatOrOpenDB];
[[self myTableView]setDelegate:self];
[[self myTableView]setDataSource:self];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)SaveFPQData
{
NSLog(#"Data Saved");
}
-(void)creatOrOpenDB
{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *docPath = [path objectAtIndex:0];
dbPathString = [docPath stringByAppendingPathComponent:#"FPQ.db"];
char *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:dbPathString]) {
const char *dbPath = [dbPathString UTF8String];
//create db
if (sqlite3_open(dbPath, &fpqDB)==SQLITE_OK) {
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS FPQ (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, CHECK INTEGER, COMMENTS TEXT)";
sqlite3_exec(fpqDB, sql_stmt, NULL, NULL, &error);
sqlite3_close(fpqDB);
}
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Actions
- (IBAction)done:(id)sender
{
[self.delegate flipsideViewControllerDidFinish:self];}
- (IBAction)deleteEntry:(id)sender {
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arrayOfCheck count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell){
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
FPQCheck *fpqCheck = [arrayOfCheck objectAtIndex:indexPath.row];
NSString *nameANDcheck = [NSString stringWithFormat:#"%#%d", fpqCheck.name, fpqCheck.check];
cell.textLabel.text = nameANDcheck;
cell.detailTextLabel.text = fpqCheck.comments;
return cell;
}
#end
You have mainly two ways:
add a property (eg. self.flipSideController) to your MainViewController to store a reference to the FlipsideViewController; then call SaveFPQData though it (eg. [self.flipSideController SaveFPQData]; or
use notification center to post a notification from saveButton: that triggers SaveFPQData; this would go like this:
//-- in flipsidecontroller `viewDidLoad`:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(SaveFPQData)
name:#"SaveFPQData"
object:nil];
//-- in saveButton:
[[NSNotificationCenter defaultCenter] postNotificationName:#"SaveFPQData" object:nil];
The second method is the simplest to implement, IMO, and it allows for the loosest coupling, at the expense of some clock cycles.
EDIT:
It is not entirely clear to me what you are trying to do (specifically, I don't understand fully how you can push the button in MainViewController once you FlipsideViewController is displayed; on the other hand, if you do not segue to the FlipsideViewController, then it is not there, so you cannot send a message to it), anyway you could try and initialise your self.flipsideViewController property in prepareForSegue:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"showAlternate"]) {
UIViewController* controller = [segue destinationViewController];
[controller setDelegate:self];
if ([controller isKindOfClass:[FlipsideViewController class]])
self.flipsideViewController = (id)controller;
}
}
after doing that, your MainViewController will be able to send the saveFPQ message to the FlipsideViewController.
If you mean you would like to send the saveFPQ message before segue-ing to the FlipsideViewController, you should make the saveButton segue to it and the call the saveFPQ method.
What I suspect is you need some kind of "model" object accessible both from the main view and the flipside view controller.
Hope this helps.

No information is passed to the DetailView Objective-c

my problem - I want to pass information from the TableView in DetailView, but somewhere in the self.detailViewController.detailItem no value is passed.
that is:
self.detailViewController.detailItem =#"123";
NSString *sss = self.detailViewController.detailItem;
NSLog(#"%#", sss);
In NSLog output (null)
Here is my source code:
DetailViewController.h
#import <UIKit/UIKit.h>
#interface DetailViewController : UIViewController <UISplitViewControllerDelegate>
#property id detailItem;
#property id TitleOfDetail;
#property (weak, nonatomic) IBOutlet UILabel *detailDescriptionLabel;
#end
DetailViewController.m
#import "DetailViewController.h"
#interface DetailViewController ()
#property (strong, nonatomic) UIPopoverController *masterPopoverController;
- (void)configureView;
#end
#implementation DetailViewController
#pragma mark - Managing the detail item
-(void)setTitleOfDetail:(id)newTitleOfDetail {
NSLog(#"123");
if (_TitleOfDetail != newTitleOfDetail) {
_TitleOfDetail = newTitleOfDetail;
// Update the view.
[self configureView];
}
}
-(void)setDetailItem:(id)newDetailItem
{
NSLog(#"123");
if (_detailItem != newDetailItem) {
_detailItem = newDetailItem;
// Update the view.
[self configureView];
}
if (self.masterPopoverController != nil) {
self.title = self.TitleOfDetail;
[self.masterPopoverController dismissPopoverAnimated:YES];
}
}
- (void)configureView
{
// Update the user interface for the detail item.
NSLog(#"1%#", self.TitleOfDetail);
NSLog(#"2%#", [self.detailItem description]);
if (self.TitleOfDetail) {
self.title = self.TitleOfDetail;
}
if (self.detailItem) {
self.detailDescriptionLabel.text = [self.detailItem description];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self configureView];
}
…
myclass.h
#class DetailViewController;
#interface myclass : UITableViewController
#property DetailViewController *detailViewController;
#end
myclass.m
#import "choiseAvtoController.h"
#import "DetailViewController.h"
#interface myclass ()
#end
#implementation myclass
#synthesize detailViewController;
…
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.detailViewController.detailItem =#"123";
NSString *sss = self.detailViewController.detailItem;
NSLog(#"%#", sss);
}
In what may be the problem and how to fix it?
P.S. Sorry for my english, I'm just learning))
Since you are using a storyboard, you should be opening the detail controller on a segue.
Look up the segue identifier (say, it's OpenDetail) in the story board, then add the following code to your initial controller:
-(void)prepareForSegue:(UIStoryboardPopoverSegue*)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"OpenDetail"]) {
DetailViewController *dest = segue.destinationViewController;
dest.detailItem =#"123";
}
}

EXC_BAD_ACCESS when I change moviePlayer contentURL

In few words, my application is doing that :
1) My main view (RootViewController) has a buton when I tap on it, it displays the player (PlayerViewController) :
2) In my Player, I initialize the video I want to play
-> It's working good, my movie is display
My problem :
When I go back to my main view :
And I tap again on the button, I get a *Program received signal: “EXC_BAD_ACCESS”.*
If I comment self.player.contentURL = [self movieURL]; it's working, but when I let it, iI have this problem.
I read that it's due to null pointer or memory problem but I don't understand why it's working the first time and not the second time. I release my object in dealloc method.
Thanks for your help !
Bruno.
Here is my code :
Root View Controller
RootViewController.h
#import <UIKit/UIKit.h>
#import "PlayerViewController.h"
#interface RootViewController : UIViewController {
IBOutlet UIButton * myButton;
}
#property (nonatomic,retain) IBOutlet UIButton * myButton;
-(IBAction)displayPlayer:(id)sender;
- (void) returnToRoot: (PlayerViewController *) controller;
#end
RootViewController.m
#import "RootViewController.h"
#implementation RootViewController
#synthesize myButton;
-(IBAction)displayPlayer:(id)sender
{
PlayerViewController *playerViewController = [[PlayerViewController alloc] initWithNibName:#"PlayerViewController" bundle:nil];
playerViewController.delegate = self;
playerViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController: playerViewController animated: YES];
[playerViewController release];
}
- (void) returnToRoot: (PlayerViewController *) controller
{
[self dismissModalViewControllerAnimated: YES];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (void)dealloc {
[super dealloc];
}
#end
Player View Controller
PlayerViewController.h
#import <UIKit/UIKit.h>
#import <MediaPlayer/MPMoviePlayerController.h>
#protocol PlayerViewControllerDelegate;
#interface PlayerViewController : UIViewController {
UIView *viewForMovie;
MPMoviePlayerController *player;
}
#property (nonatomic, assign) id <PlayerViewControllerDelegate> delegate;
#property (nonatomic, retain) IBOutlet UIView *viewForMovie;
#property (nonatomic, retain) MPMoviePlayerController *player;
- (NSURL *)movieURL;
-(IBAction)goBackToRoot:(id)sender;
#end
#protocol PlayerViewControllerDelegate
- (void) returnToRoot: (PlayerViewController *) controller;
#end
PlayerViewController.m
#import "PlayerViewController.h"
#implementation PlayerViewController
#synthesize player;
#synthesize viewForMovie;
#synthesize delegate;
- (void)dealloc {
[super dealloc];
[player release];
[viewForMovie release];
}
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"viewDidLoad");
self.player = [[MPMoviePlayerController alloc] init];
[self.player autorelease];
self.player.view.frame = self.viewForMovie.bounds;
self.player.view.autoresizingMask =
UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight;
[self.viewForMovie addSubview:player.view];
self.player.contentURL = [self movieURL];
[self.player play];
}
-(NSURL *)movieURL
{
NSBundle *bundle = [NSBundle mainBundle];
NSString *moviePath =
[bundle
pathForResource:#"myVideo"
ofType:#"mp4"];
if (moviePath) {
return [NSURL fileURLWithPath:moviePath];
} else {
return nil;
}
}
-(IBAction)goBackToRoot:(id)sender{
[self.delegate returnToRoot: self];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
#end
Problem
The second time I call "displayPlayer" I had the EXC_BAD_ACCESS
I solved it !!!
I look on the MPMoviePlayerController to see what kind of variable is contentURL
(NSURL *)contentURL
It means I have also to liberate it.
I do that in my dealloc method putting a nil value:
-(void) dealloc {
[super dealloc];
self.player.contentURL = nil;
[player release];
[viewForMovie release];
}
If I comment self.player.contentURL =
[self movieURL]; it's working, but
when I let it, iI have this problem.
In that case, how is contentURL declared? Does the #property definition include copy or retain?