Wednesday, 28 August 2013

Simple Application Development iOS

I like to add some Applications that developed using Objective C here along with coding comments.So users can easily understand the code and they can customize their own way. Most of the application that iam going to add here from  Github(Open source codes) .



Movie ,Video streaming Player 

  • Documentation:

    Demonstrates how to use the Media Player Framework to play a movie in a custom view. The sample will play either a local movie file or a movie loaded from a network-based URL. The sample also contains code to configure the movie playback controls, scaling mode, background color, background view, application audio session and repeat mode when transitioning to and from movie playback.

    The Media Player framework provides basic facilities for playing movie files. Within the Media Player framework, a MPMoviePlayerController object defines a movie player. You can use this class to play back movies stored in your application’s bundle directory or support directories. You can also use it to play movies loaded from a network-based URL. With iPhone OS version 3.0 or later, iPhone is capable of receiving streaming audio and video over HTTP from an ordinary web server.

    Supported Formats

    The MPMoviePlayerController class supports any movie or audio files that already play correctly on an iPod, iPhone or iPad. For movie files, this typically means files with the extensions .m4v, .mov, .mp4 and .3gp and using one of the supported compression standards. Here's a sampling of the supported formats for the iPhone 4, iPod Touch and iPad:

    iPhone 4

    H.264 video up to 720p, 30 frames per second, Main Profile level 3.1 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second, Simple Profile with AAC-LC audio up to 160 Kbps per channel, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; Motion JPEG (M-JPEG) up to 35 Mbps, 1280 by 720 pixels, 30 frames per second, audio in ulaw, PCM stereo audio in .avi file format

    iPad

    H.264 video up to 720p, 30 frames per second, Main Profile level 3.1 with AAC-LC audio up to 160 Kbps per channel, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second, Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; Motion JPEG (M-JPEG) up to 35 Mbps, 1280 by 720 pixels, 30 frames per second, audio in ulaw, PCM stereo audio in .avi file format

    iPod Touch (4th Generation)

    H.264 video up to 720p, 30 frames per second, Main Profile level 3.1 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats

    MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second, Simple Profile with AAC-LC audio up to 160 Kbps per channel, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats

    Motion JPEG (M-JPEG) up to 35 Mbps, 1280 by 720 pixels, 30 frames per second, audio in ulaw, PCM stereo audio in .avi file format

    If you use the MPMoviePlayerController class to play audio files, it displays a QuickTime logo while the audio plays. For audio files, this class class supports AAC-LC audio at up to 48 kHz, and MP3 (MPEG-1 Audio Layer 3) up to 48 kHz, stereo audio.

    Media Delivery

    iPhone can display movie files delivered by any web server using HTTP protocols. Refer to your web server documentation to learn how to configure your web server for movie file delivery. This means movie files shared on a user's MobileMe iDisk can be displayed on iPhone.  See the Apple MobileMe website to learn how to share files with your MobileMe iDisk.

    When a file is delivered over a network or downloaded over the Internet, the entire file is not available immediately, but a typical QuickTime movie can be played while it downloads. This is called progressive download, or Fast Start. It works because the movie atom is stored at the beginning of the file, so QuickTime knows how to interpret the movie sample data even before it arrives, and because the movie data is intelligently interleaved with respect to display time. 

    It is also possible to create a movie file with the sample data stored first, followed by the movie data structure. This is not usually desirable, because the entire file must download before QuickTime can interpret the sample data. You can correct this kind of data inversion simply by opening the movie file in QuickTime and saving it as a new, self-contained file. QuickTime stores the movie data structure at the beginning of the file by default.

    With iPhone 3.0 or later, iPhone is capable of receiving streaming audio and video over HTTP from an ordinary web server. Currently, the supported format is MPEG-2 transport streams containing H.264 video and HE-AAC audio. Audio-only streams can be either HE-AAC with ADTS headers, or MP3. In a typical configuration, a hardware encoder takes audio-video input and turns it into an MPEG-2 transport stream, which is then broken into a series of short media files by a software stream segmenter. The segmenter also creates and maintains an index file containing a list of the media files. 

    The URL of the index file is published on the web server, which responds to file requests in the usual way. The client software reads the index, then requests the listed media files in order and displays them without any pauses or gaps between segments. Media segments are saved as .ts files (MPEG-2 streams) and index files are saved as .m3u8 files, an extension of the .m3u format used for MP3 playlists. For more information about streaming audio and video over HTTP for iPhone, see the "HTTP Live Streaming Overview" document which is available on the iPhone Developer Center.

    Using the Application

    After the application launches, press the Tab Bar labeled "Local" to go to the application screen to play the local movie file that is stored in the application bundle. Press the Play Movie button (or touch anywhere in the movie preview image) and the local movie file will play full-screen. When launched, notice the background color, playback controls and scaling mode. Touch anywhere on the movie during playback and the playback controls will show (unless you've turned them off via the "Settings" application). Also notice the custom overlay controls that are drawn on top of the movie. Touches anywhere on the overlay controls are handled specifically by the application, not by the movie player. 

    Press the Tab Bar labeled "Streaming" go to the application view to play movies loaded from a network-based URL.  Enter a valid movie URL and press the Play Movie button to begin playback (Note: for MPEG-2 transport streams this would be the URL of the index file, for example http://media.example.com/mymedia/index.m3u8). Touch anywhere on the screen during playback to display the movie playback controls. Touch the screen again to make them go away.

    Quit the application and go to the Springboard to launch the built-in "Settings" application. Scroll down and you will find a section for "MoviePlayer". Open it and from there you can set the background color, background image, playback controls, repeat mode, application audio setting and scaling mode. Quit Settings and return to MoviePlayer. Press the Play Movie button again and notice the above settings have changed. 

    This sample offers an Xcode project already pre-configured to build your Settings bundle as a target. To customize your settings UI, change the Root.plist file.

    ====================================================================
    BUILD REQUIREMENTS:

    Xcode 4, iOS SDK 4.3 or better

    ====================================================================
    RUNTIME REQUIREMENTS:

    iPhone, iPad or iPod Touch running iOS 4.0 or better

    ====================================================================
    PACKAGING LIST:

    MoviePlayerAppDelegate.h
    MoviePlayerAppDelegate.m
    A simple UIApplication delegate class that adds the MyMovieViewController view to the window as a subview. Instantiates a MPMoviePlayerController object and begins movie playback. 

    MyMovieViewController.h
    MyMovieViewController.m
    A UIViewController controller subclass that implements a movie playback view. Uses a MyMovieController object to control playback of a movie.
    Adds and removes an overlay view to the view hierarchy. Handles button presses to the 'Close Movie' button in the overlay view.
    Adds and removes a background view to hide any underlying user interface controls when playing a movie. Gets user movie settings preferences by calling the MoviePlayerUserPref methods. Apply these settings to the movie with the MyMovieController movie object.
    </abstract>

    MyLocalMovieViewController.h
    MyLocalMovieViewController.m
    Subclass of MyMovieViewController. Gives a URL to a local movie stored in the app bundle. Implements a 'Play Movie' button for playback of a local movie. Also plays the local movie on touches to the UIImageView. 

    MyStreamingMovieViewController.h
    MyStreamingMovieViewController.m
    A UIViewController controller subclass that loads the SecondView nib file that contains its view. Contains an action method that is called when the Play Movie button is tapped to play the movie. Provides a text edit control for the user to enter a movie URL. Overrides the inherited shouldAutorotateToInterfaceOrientation: method so that the view can respond to device rotation.

    MyImageView.h
    MyImageView.m
    A UIImageView subclass that implements the UIResponder event-handling method touchesBegan: withEvent: in order to receive finger touch event messages. Any finger touch events in this view will start the movie playing.

    MyOverlayViewController.h
    MyOverlayViewController.m
    A UIViewController controller subclass that implements an overlay view to display movie load state and playback state and a button to close the active movie. Contains an action method that is called when the 'Close Movie' button is pressed to close the movie.

    MoviePlayerUserPrefs.h
    MoviePlayerUserPrefs.m
    Contains methods to get the application user preferences settings for the movie scaling mode, control style, background color, repeat mode, application audio session and background image.

    MainWindow.xib
    Interface Builder 'nib' file that defines the iPhone interface for the application: the main window, the view and other user interface items. Also contains the movie file used for playback, and the plist files defining the application movie playback settings.

    SecondView.xib
    Interface Builder 'nib' file that defines the iPhone interface for the streaming movie window, view, movie URL text edit control and other user interface items.

    MainWindow-iPad.xib
    Interface Builder 'nib' file that defines the iPad interface for the application: the main window, the view and other user interface items. Also contains the movie file used for playback, and the plist files defining the application movie playback settings.

    SecondView-iPad.xib
    Interface Builder 'nib' file that defines the iPad interface for the streaming movie window, view, movie URL text edit control and other user interface items.

    main.m
    Entry point for the application. Creates the application object and causes the event loop to start.

    Root.plist
    The scheme file for the settings bundle.

    Movie.m4v
    The movie file to be played.

  • Design
  •  iPhone Design


  • Code
File structure



MoviePlayerAppDelegate.h

#import <UIKit/UIKit.h>
#import <MediaPlayer/MediaPlayer.h>

@interface MoviePlayerAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate> 
{
    IBOutlet UIWindow *window;
    IBOutlet UITabBarController *tabBarController;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UITabBarController *tabBarController;

@end


MoviePlayerAppDelegate.m

#import "MoviePlayerAppDelegate.h"
#import "MyMovieViewController.h"

@implementation MoviePlayerAppDelegate

@synthesize window;
@synthesize tabBarController;

- (void)applicationDidFinishLaunching:(UIApplication *)application 
{   
    /* Override point for customization after app. launch. */

    /* Add the tab bar controller's current view as a subview of the window. */
    [window addSubview:tabBarController.view];
    [window makeKeyAndVisible];    
}

/* Tells the delegate that the application is about to enter the foreground. */
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    MyMovieViewController *selectedViewController = (MyMovieViewController *)tabBarController.selectedViewController;
    if ([selectedViewController respondsToSelector:@selector(viewWillEnterForeground)])
    {
        [selectedViewController viewWillEnterForeground]; 
    }
}

- (void)dealloc 
{
    [window release];
    [super dealloc];
}


@end


MyMovieViewController.h

#import <UIKit/UIKit.h>
#import <MediaPlayer/MediaPlayer.h>

#import "MoviePlayerAppDelegate.h"
#import "MyOverlayViewController.h"

@class MyImageView;

@interface MyMovieViewController : UIViewController 
{
@private
    MPMoviePlayerController *moviePlayerController;
    
    IBOutlet MoviePlayerAppDelegate *appDelegate;

    IBOutlet MyImageView *imageView;
    IBOutlet UIImageView *movieBackgroundImageView;
    IBOutlet UIView *backgroundView;    
    IBOutlet MyOverlayViewController *overlayController;       
}

@property (nonatomic, retain) IBOutlet MyImageView *imageView;
@property (nonatomic, retain) IBOutlet UIImageView *movieBackgroundImageView;
@property (nonatomic, retain) IBOutlet UIView *backgroundView;
@property (nonatomic, retain) IBOutlet MyOverlayViewController *overlayController;

@property (nonatomic, retain) IBOutlet MoviePlayerAppDelegate *appDelegate;

@property (retain) MPMoviePlayerController *moviePlayerController;

- (IBAction)overlayViewCloseButtonPress:(id)sender;
- (void)viewWillEnterForeground;
- (void)playMovieFile:(NSURL *)movieFileURL;
- (void)playMovieStream:(NSURL *)movieFileURL;

@end


MyMovieViewController.m

#import "MyMovieViewController.h"
#import "MoviePlayerUserPrefs.h"

CGFloat kMovieViewOffsetX = 20.0;
CGFloat kMovieViewOffsetY = 20.0;

@interface MyMovieViewController (OverlayView)

-(void)addOverlayView;
-(void)removeOverlayView;
-(void)resizeOverlayWindow;

@end

@interface MyMovieViewController(MovieControllerInternal)
-(void)createAndPlayMovieForURL:(NSURL *)movieURL sourceType:(MPMovieSourceType)sourceType;
-(void)applyUserSettingsToMoviePlayer;
-(void)moviePlayBackDidFinish:(NSNotification*)notification;
-(void)loadStateDidChange:(NSNotification *)notification;
-(void)moviePlayBackStateDidChange:(NSNotification*)notification;
-(void)mediaIsPreparedToPlayDidChange:(NSNotification*)notification;
-(void)installMovieNotificationObservers;
-(void)removeMovieNotificationHandlers;
-(void)deletePlayerAndNotificationObservers;
@end

@interface MyMovieViewController (ViewController)
-(void)removeMovieViewFromViewHierarchy;
@end

@implementation MyMovieViewController(ViewController)

#pragma mark View Controller

/* Sent to the view controller after the user interface rotates. */
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    /* Size movie view to fit parent view. */
    CGRect viewInsetRect = CGRectInset ([self.view bounds],
                                        kMovieViewOffsetX,
                                        kMovieViewOffsetY );
    [[[self moviePlayerController] view] setFrame:viewInsetRect];

    /* Size the overlay view for the current orientation. */
    [self resizeOverlayWindow];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{
    /* Return YES for supported orientations. */
    return YES;
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (void)viewDidUnload
{
    [self deletePlayerAndNotificationObservers];
    
    [super viewDidUnload];
}

/* Notifies the view controller that its view is about to be become visible. */
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    /* Size the overlay view for the current orientation. */
    [self resizeOverlayWindow];
    /* Update user settings for the movie (in case they changed). */
    [self applyUserSettingsToMoviePlayer];
}

/* Notifies the view controller that its view is about to be dismissed, 
 covered, or otherwise hidden from view. */
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    /* Remove the movie view from the current view hierarchy. */
    [self removeMovieViewFromViewHierarchy];
    /* Removie the overlay view. */
    [self removeOverlayView];
    /* Remove the background view. */
    [self.backgroundView removeFromSuperview];
    
    /* Delete the movie player object and remove the notification observers. */
    [self deletePlayerAndNotificationObservers];
}

- (void)dealloc 
{   
    [self setMoviePlayerController:nil];
    self.imageView = nil;
    self.movieBackgroundImageView = nil;
    self.backgroundView = nil;
    self.overlayController = nil;

    [super dealloc];
}

/* Remove the movie view from the view hierarchy. */
-(void)removeMovieViewFromViewHierarchy
{
    MPMoviePlayerController *player = [self moviePlayerController];
    
    [player.view removeFromSuperview];
}

#pragma mark Error Reporting

-(void)displayError:(NSError *)theError
{
    if (theError)
    {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle: @"Error"
                              message: [theError localizedDescription]
                              delegate: nil
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
}

@end

#pragma mark -
@implementation MyMovieViewController (OverlayView)


/* Add an overlay view on top of the movie. This view will display movie
 play states and includes a 'Close Movie' button. */
-(void)addOverlayView
{
    MPMoviePlayerController *player = [self moviePlayerController];
    
    if (!([self.overlayController.view isDescendantOfView:self.view])
        && ([player.view isDescendantOfView:self.view])) 
    {
        // add an overlay view to the window view hierarchy
        [self.view addSubview:self.overlayController.view];
    }
}

/* Remove overlay view from the view hierarchy. */
-(void)removeOverlayView
{
    [self.overlayController.view removeFromSuperview];
}

-(void)resizeOverlayWindow
{
    CGRect frame = self.overlayController.view.frame;
    frame.origin.x = round((self.view.frame.size.width - frame.size.width) / 2.0);
    frame.origin.y = round((self.view.frame.size.height - frame.size.height) / 2.0);
    self.overlayController.view.frame = frame;
}

@end

#pragma mark -
@implementation MyMovieViewController

@synthesize moviePlayerController;

@synthesize imageView;
@synthesize movieBackgroundImageView;
@synthesize backgroundView;
@synthesize overlayController;

@synthesize appDelegate;

/* Action method for the overlay view 'Close Movie' button.
 Remove the movie view and overlay view from the window,
 dispose the movie object and remove the notification
 handlers. */
-(IBAction)overlayViewCloseButtonPress:(id)sender
{
    [[self moviePlayerController] stop];
    
    [self removeMovieViewFromViewHierarchy];
    
    [self removeOverlayView];
    [self.backgroundView removeFromSuperview];
    
    [self deletePlayerAndNotificationObservers];
}

/*  
 Called by the MoviePlayerAppDelegate (UIApplicationDelegate protocol) 
 applicationWillEnterForeground when the app is about to enter
 the foreground.
 */
- (void)viewWillEnterForeground
{
    /* Set the movie object settings (control mode, background color, and so on) 
       in case these changed. */
    [self applyUserSettingsToMoviePlayer];
}

#pragma mark Play Movie Actions

/* Called soon after the Play Movie button is pressed to play the local movie. */
-(void)playMovieFile:(NSURL *)movieFileURL
{
    [self createAndPlayMovieForURL:movieFileURL sourceType:MPMovieSourceTypeFile];   
}

/* Called soon after the Play Movie button is pressed to play the streaming movie. */
-(void)playMovieStream:(NSURL *)movieFileURL
{
    MPMovieSourceType movieSourceType = MPMovieSourceTypeUnknown;
    /* If we have a streaming url then specify the movie source type. */
    if ([[movieFileURL pathExtension] compare:@"m3u8" options:NSCaseInsensitiveSearch] == NSOrderedSame) 
    {
        movieSourceType = MPMovieSourceTypeStreaming;
    }
    [self createAndPlayMovieForURL:movieFileURL sourceType:movieSourceType];   
}

@end

#pragma mark -
#pragma mark Movie Player Controller Methods
#pragma mark -

@implementation MyMovieViewController (MovieControllerInternal)

#pragma mark Create and Play Movie URL

/*
 Create a MPMoviePlayerController movie object for the specified URL and add movie notification
 observers. Configure the movie object for the source type, scaling mode, control style, background
 color, background image, repeat mode and AirPlay mode. Add the view containing the movie content and 
 controls to the existing view hierarchy.
 */
-(void)createAndConfigurePlayerWithURL:(NSURL *)movieURL sourceType:(MPMovieSourceType)sourceType 
{    
    /* Create a new movie player object. */
    MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
    
    if (player) 
    {
        /* Save the movie object. */
        [self setMoviePlayerController:player];
        
        /* 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. */
        [self.view addSubview:self.backgroundView];
        
        CGRect viewInsetRect = CGRectInset ([self.view bounds],
                                            kMovieViewOffsetX,
                                            kMovieViewOffsetY );
        /* Inset the movie frame in the parent view frame. */
        [[player view] setFrame:viewInsetRect];
        
        [player view].backgroundColor = [UIColor lightGrayColor];
        
        /* 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. */
        [self.view addSubview: [player view]];        
    }    
}

/* Load and play the specified movie url with the given file type. */
-(void)createAndPlayMovieForURL:(NSURL *)movieURL sourceType:(MPMovieSourceType)sourceType
{
    [self createAndConfigurePlayerWithURL:movieURL sourceType:sourceType];
        
    /* Play the movie! */
    [[self moviePlayerController] play];
}

#pragma mark Movie Notification Handlers

/*  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];
            [self removeOverlayView];
            [self.backgroundView removeFromSuperview];
            break;
            
            /* The user stopped playback. */
        case MPMovieFinishReasonUserExited:
            [self removeMovieViewFromViewHierarchy];
            [self removeOverlayView];
            [self.backgroundView removeFromSuperview];
            break;
            
        default:
            break;
    }
}

/* Handle movie load state changes. */
- (void)loadStateDidChange:(NSNotification *)notification 
{   
    MPMoviePlayerController *player = notification.object;
    MPMovieLoadState loadState = player.loadState;  
    
    /* The load state is not known at this time. */
    if (loadState & MPMovieLoadStateUnknown)
    {
        [self.overlayController setLoadStateDisplayString:@"n/a"];

        [overlayController setLoadStateDisplayString:@"unknown"];       
    }
    
    /* The buffer has enough data that playback can begin, but it 
     may run out of data before playback finishes. */
    if (loadState & MPMovieLoadStatePlayable)
    {
        [overlayController setLoadStateDisplayString:@"playable"];
    }
    
    /* Enough data has been buffered for playback to continue uninterrupted. */
    if (loadState & MPMovieLoadStatePlaythroughOK)
    {
        // Add an overlay view on top of the movie view
        [self addOverlayView];
        
        [overlayController setLoadStateDisplayString:@"playthrough ok"];
    }
    
    /* The buffering of data has stalled. */
    if (loadState & MPMovieLoadStateStalled)
    {
        [overlayController setLoadStateDisplayString:@"stalled"];
    }
}

/* Called when the movie playback state has changed. */
- (void) moviePlayBackStateDidChange:(NSNotification*)notification
{
    MPMoviePlayerController *player = notification.object;
    
    /* Playback is currently stopped. */
    if (player.playbackState == MPMoviePlaybackStateStopped) 
    {
        [overlayController setPlaybackStateDisplayString:@"stopped"];
    }
    /*  Playback is currently under way. */
    else if (player.playbackState == MPMoviePlaybackStatePlaying) 
    {
        [overlayController setPlaybackStateDisplayString:@"playing"];
    }
    /* Playback is currently paused. */
    else if (player.playbackState == MPMoviePlaybackStatePaused) 
    {
        [overlayController setPlaybackStateDisplayString:@"paused"];
    }
    /* Playback is temporarily interrupted, perhaps because the buffer 
     ran out of content. */
    else if (player.playbackState == MPMoviePlaybackStateInterrupted) 
    {
        [overlayController setPlaybackStateDisplayString:@"interrupted"];
    }
}

/* Notifies observers of a change in the prepared-to-play state of an object 
 conforming to the MPMediaPlayback protocol. */
- (void) mediaIsPreparedToPlayDidChange:(NSNotification*)notification
{
    // Add an overlay view on top of the movie view
    [self addOverlayView];
}

#pragma mark Install Movie Notifications

/* Register observers for the various movie object notifications. */
-(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];        
}

#pragma mark Remove Movie Notification Handlers

/* Remove the movie notification observers from the movie object. */
-(void)removeMovieNotificationHandlers
{    
    MPMoviePlayerController *player = [self moviePlayerController];
    
    [[NSNotificationCenter defaultCenter]removeObserver:self name:MPMoviePlayerLoadStateDidChangeNotification object:player];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:player];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:MPMediaPlaybackIsPreparedToPlayDidChangeNotification object:player];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:MPMoviePlayerPlaybackStateDidChangeNotification object:player];
}

/* Delete the movie player object, and remove the movie notification observers. */
-(void)deletePlayerAndNotificationObservers
{
    [self removeMovieNotificationHandlers];
    [self setMoviePlayerController:nil];
}

#pragma mark Movie Settings

/* Apply user movie preference settings (these are set from the Settings: iPhone Settings->Movie Player)
   for scaling mode, control style, background color, repeat mode, application audio session, background
   image and AirPlay mode. 
 */
-(void)applyUserSettingsToMoviePlayer
{
    MPMoviePlayerController *player = [self moviePlayerController];
    if (player) 
    {
        player.scalingMode = [MoviePlayerUserPrefs scalingModeUserSetting];
        player.controlStyle =[MoviePlayerUserPrefs controlStyleUserSetting];    
        player.backgroundView.backgroundColor = [MoviePlayerUserPrefs backgroundColorUserSetting];
        player.repeatMode = [MoviePlayerUserPrefs repeatModeUserSetting];
        player.useApplicationAudioSession = [MoviePlayerUserPrefs audioSessionUserSetting];
        if ([MoviePlayerUserPrefs backgroundImageUserSetting] == YES)
        {
            [self.movieBackgroundImageView setFrame:[self.view bounds]];
            [player.backgroundView addSubview:self.movieBackgroundImageView];
        }
        else
        {
            [self.movieBackgroundImageView removeFromSuperview];
        }
        
        /* Indicate the movie player allows AirPlay movie playback. */
        player.allowsAirPlay = YES;        
    }
}



@end




MyLocalMovieViewController.h


#import <UIKit/UIKit.h>
#import "MyMovieViewController.h"


@interface MyLocalMovieViewController : MyMovieViewController 
{
}

-(IBAction)playMovieButtonPressed:(id)sender;

@end



MyLocalMovieViewController.m



#import "MyLocalMovieViewController.h"

@interface MyLocalMovieViewController (LocalMovieURL)
-(NSURL *)localMovieURL;
@end

#pragma mark -
@implementation MyLocalMovieViewController (LocalMovieURL)

/* Returns a URL to a local movie in the app bundle. */
-(NSURL *)localMovieURL
{
    NSURL *theMovieURL = nil;
    NSBundle *bundle = [NSBundle mainBundle];
    if (bundle) 
    {
        NSString *moviePath = [bundle pathForResource:@"Movie" ofType:@"m4v"];
        if (moviePath)
        {
            theMovieURL = [NSURL fileURLWithPath:moviePath];
        }
    }
    return theMovieURL;
}

@end

#pragma mark -

@implementation MyLocalMovieViewController

/* Button presses for the 'Play Movie' button. */
-(IBAction)playMovieButtonPressed:(id)sender
{
    /* Play the movie at the specified URL. */
    [self playMovieFile:[self localMovieURL]];
}


@end


MyImageView.h

#import <UIKit/UIKit.h>
#import "MyLocalMovieViewController.h"

@interface MyImageView : UIImageView 
{
    IBOutlet MyLocalMovieViewController *viewController;
}

@property (nonatomic,retain) IBOutlet MyLocalMovieViewController *viewController;

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;

@end


MyImageView.m

#import "MyImageView.h"


@implementation MyImageView

@synthesize viewController;

/* Touches to the Image view will start the movie playing. */
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
    UITouch* touch = [touches anyObject];
    if (touch.phase == UITouchPhaseBegan)
    {
        /* play the movie! */
        [self.viewController playMovieButtonPressed:self];
    }    
}


@end


MyStreamingMovieViewController.h

#import <UIKit/UIKit.h>
#import "MoviePlayerAppDelegate.h"
#import "MyMovieViewController.h"

@interface MyStreamingMovieViewController : MyMovieViewController <UITextFieldDelegate> 
{
@private
    IBOutlet UITextField *movieURLTextField;
}

@property (nonatomic,retain) IBOutlet UITextField *movieURLTextField;

-(IBAction)playStreamingMovieButtonPressed:(id)sender;

@end



MyStreamingMovieViewController.m

#import "MyStreamingMovieViewController.h"

@implementation MyStreamingMovieViewController

@synthesize movieURLTextField;

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField 
{
    UITextField *movieURLText = self.movieURLTextField;
    /* When the user presses return, take focus away from the 
     text field so that the keyboard is dismissed. */
    if (theTextField == movieURLText) {
        [movieURLText resignFirstResponder];
    }
    return YES;
}

/* Handle touches to the 'Play Movie' button. */
-(IBAction)playStreamingMovieButtonPressed:(id)sender
{
    /* Has the user entered a movie URL? */
    if (self.movieURLTextField.text.length > 0)
    {
        NSURL *theMovieURL = [NSURL URLWithString:self.movieURLTextField.text];
        if (theMovieURL)
        {
            if ([theMovieURL scheme])   // sanity check on the URL
            {
                /* Play the movie with the specified URL. */
                [self playMovieStream:theMovieURL];
            }
        }
    }
}


@end


MyOverlayViewController.h


#import <UIKit/UIKit.h>


@interface MyOverlayViewController : UIViewController 
{
@private
    IBOutlet UILabel *moviePlaybackStateText;
    IBOutlet UILabel *movieLoadStateText;
}

@property (nonatomic, retain) IBOutlet UILabel *moviePlaybackStateText;
@property (nonatomic, retain) IBOutlet UILabel *movieLoadStateText;

- (void)setPlaybackStateDisplayString:(NSString *)playBackText;
- (void)setLoadStateDisplayString:(NSString *)loadStateText;

@end


MyOverlayViewController.m

#import "MyOverlayViewController.h"

@implementation MyOverlayViewController

@synthesize moviePlaybackStateText, movieLoadStateText;

#pragma mark -
#pragma mark Display Movie Status Strings

/* Movie playback state display string. */
-(void)setPlaybackStateDisplayString:(NSString *)playBackText
{
    self.moviePlaybackStateText.text = playBackText;
}

/* Movie load state display string. */
-(void)setLoadStateDisplayString:(NSString *)loadStateText;
{
    self.movieLoadStateText.text = loadStateText;
}

@end


MoviePlayerUserPrefs.h

#import <Foundation/Foundation.h>
#import <MediaPlayer/MediaPlayer.h>

@interface MoviePlayerUserPrefs : NSObject 
{
}

+ (MPMovieScalingMode)scalingModeUserSetting;
+ (MPMovieControlStyle)controlStyleUserSetting;
+ (UIColor *)backgroundColorUserSetting;
+ (MPMovieRepeatMode)repeatModeUserSetting;
+ (BOOL)audioSessionUserSetting;
+ (BOOL)backgroundImageUserSetting;

@end


MoviePlayerUserPrefs.m

#import "MoviePlayerUserPrefs.h"

// Application preference keys
NSString *kScalingModeKey                   = @"scalingMode";
NSString *kControlStyleKey                  = @"controlStyle";
NSString *kBackgroundColorKey               = @"backgroundColor";
NSString *kRepeatModeKey                    = @"repeatMode";
NSString *kUseApplicationAudioSessionKey    = @"useApplicationAudioSession";
NSString *kMovieBackgroundImageKey          = @"useMovieBackgroundImage";


@implementation MoviePlayerUserPrefs

#pragma mark Movie User Preference Settings

+ (void)registerDefaults
{
    /* First get the movie player settings defaults (scaling, controller type, background color,
     repeat mode, application audio session) set by the user via the built-in iPhone Settings 
     application */
     
    NSString *testValue = [[NSUserDefaults standardUserDefaults] stringForKey:kScalingModeKey];
    if (testValue == nil)
    {
        // No default movie player settings values have been set, create them here based on our 
        // settings bundle info.
        //
        // The values to be set for movie playback are:
        //
        //    - scaling mode (None, Aspect Fill, Aspect Fit, Fill)
        //    - controller style (None, Fullscreen, Embedded)
        //    - background color (Any UIColor value)
        //    - repeat mode (None, One)
        //    - use application audio session (On, Off)
        //    - background image
        
        NSString *pathStr = [[NSBundle mainBundle] bundlePath];
        NSString *settingsBundlePath = [pathStr stringByAppendingPathComponent:@"Settings.bundle"];
        NSString *finalPath = [settingsBundlePath stringByAppendingPathComponent:@"Root.plist"];
        
        NSDictionary *settingsDict = [NSDictionary dictionaryWithContentsOfFile:finalPath];
        NSArray *prefSpecifierArray = [settingsDict objectForKey:@"PreferenceSpecifiers"];
        
        NSNumber *controlStyleDefault = nil;
        NSNumber *scalingModeDefault = nil;
        NSNumber *backgroundColorDefault = nil;
        NSNumber *repeatModeDefault = nil;
        NSNumber *useApplicationAudioSession = nil;
        NSNumber *movieBackgroundImageDefault = nil;
        
        NSDictionary *prefItem;
        for (prefItem in prefSpecifierArray)
        {
            NSString *keyValueStr = [prefItem objectForKey:@"Key"];
            id defaultValue = [prefItem objectForKey:@"DefaultValue"];
            
            if ([keyValueStr isEqualToString:kScalingModeKey])
            {
                scalingModeDefault = defaultValue;
            }
            else if ([keyValueStr isEqualToString:kControlStyleKey])
            {
                controlStyleDefault = defaultValue;
            }
            else if ([keyValueStr isEqualToString:kBackgroundColorKey])
            {
                backgroundColorDefault = defaultValue;
            }
            else if ([keyValueStr isEqualToString:kRepeatModeKey])
            {
                repeatModeDefault = defaultValue;
            }
            else if ([keyValueStr isEqualToString:kUseApplicationAudioSessionKey])
            {
                useApplicationAudioSession = defaultValue;
            }
            else if ([keyValueStr isEqualToString:kMovieBackgroundImageKey])
            {
                movieBackgroundImageDefault = defaultValue;
            }
        }
        
        // since no default values have been set, create them here
        NSDictionary *appDefaults =  [NSDictionary dictionaryWithObjectsAndKeys:
                                      scalingModeDefault, kScalingModeKey,
                                      controlStyleDefault, kControlStyleKey,
                                      backgroundColorDefault, kBackgroundColorKey,
                                      repeatModeDefault, kRepeatModeKey,
                                      useApplicationAudioSession, kUseApplicationAudioSessionKey,
                                      movieBackgroundImageDefault, kMovieBackgroundImageKey,
                                      nil];
        
        [[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    else 
    {
        /*
            Writes any modifications to the persistent domains to disk and updates all unmodified 
            persistent domains to what is on disk.
        */
        [[NSUserDefaults standardUserDefaults] synchronize];
    }


}

+(MPMovieScalingMode)scalingModeUserSetting
{
    [self registerDefaults];

    /* 
        Movie scaling mode can be one of: MPMovieScalingModeNone, MPMovieScalingModeAspectFit,
            MPMovieScalingModeAspectFill, MPMovieScalingModeFill.
            
        Movie scaling mode describes how the movie content is scaled to fit the frame of its view.
        It may be one of:

            MPMovieScalingModeNone, MPMovieScalingModeAspectFit, MPMovieScalingModeAspectFill,
            MPMovieScalingModeFill.
   */
    return([[NSUserDefaults standardUserDefaults] integerForKey:kScalingModeKey]);
}

+(MPMovieControlStyle)controlStyleUserSetting
{
    [self registerDefaults];

    /* 
        Movie control style can be one of: MPMovieControlStyleNone, MPMovieControlStyleEmbedded,
            MPMovieControlStyleFullscreen.
            
        Movie control style describes the style of the playback controls.
        It can be one of:
            
            MPMovieControlStyleNone, MPMovieControlStyleEmbedded, MPMovieControlStyleFullscreen,
            MPMovieControlStyleDefault, MPMovieControlStyleFullscreen
   */

    return([[NSUserDefaults standardUserDefaults] integerForKey:kControlStyleKey]);
}

+(UIColor *)backgroundColorUserSetting
{
    [self registerDefaults];

    /*
        The color of the background area behind the movie can be any UIColor value.
    */
    UIColor *colors[15] = {[UIColor blackColor], [UIColor darkGrayColor], [UIColor lightGrayColor], [UIColor whiteColor], 
        [UIColor grayColor], [UIColor redColor], [UIColor greenColor], [UIColor blueColor], [UIColor cyanColor], 
        [UIColor yellowColor], [UIColor magentaColor],[UIColor orangeColor], [UIColor purpleColor], [UIColor brownColor], 
        [UIColor clearColor]};
    return (colors[ [[NSUserDefaults standardUserDefaults] integerForKey:kBackgroundColorKey] ] );
}

+(MPMovieRepeatMode)repeatModeUserSetting
{
    [self registerDefaults];

    /* 
        Movie repeat mode describes how the movie player repeats content at the end of playback.
    
        Movie repeat mode can be one of: MPMovieRepeatModeNone, MPMovieRepeatModeOne.
            
   */
    return([[NSUserDefaults standardUserDefaults] integerForKey:kRepeatModeKey]);
}

+(BOOL)audioSessionUserSetting
{
    [self registerDefaults];
    /* 
        Movie Use Application Audio Session mode indicates whether the movie player should use the application’s audio session.
    
        Use Application Audio Session mode can be one of: On, Off.
            
   */
    return([[NSUserDefaults standardUserDefaults] integerForKey:kUseApplicationAudioSessionKey]);
}

+(BOOL)backgroundImageUserSetting
{
    [self registerDefaults];

    return([[NSUserDefaults standardUserDefaults] integerForKey:kMovieBackgroundImageKey]);
}

@end


No comments:

Post a Comment