How to show Interstitial once in ios app? - ios

Every time I open category the Interstitial appears I want to make it appears once
the code
//----------Interstitial Initialization-------------//
-(void)createAndLoadInterstitial
{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
_interstitial = [[GADInterstitial alloc] initWithAdUnitID:appDelegate.InterstitialAdUnitID];
_interstitial.delegate = self;
[_interstitial loadRequest:[GADRequest request]];
}
- (void)interstitialDidReceiveAd:(GADInterstitial *)interstitial
{
[_interstitial presentFromRootViewController:self];
}
- (void)interstitial:(GADInterstitial *)interstitial didFailToReceiveAdWithError:(GADRequestError *)error
{
NSLog(#"interstitialDidFailToReceiveAdWithError: %#", [error localizedDescription]);
}
- (void)interstitialDidDismissScreen:(GADInterstitial *)interstitial
{
NSLog(#"interstitialDidDismissScreen");
}

Try this
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//call your method here
[self createAndLoadInterstitial];
});

Related

I want to open fullscreen with the wkwebview in the banner? objective-c

-(void) openPopUpWithUrl:(NSString*)urlString{
AppDelegate* appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
ExtraWebViewController* extraWebView = [[ExtraWebViewController alloc] init];
extraWebView.url = urlString;
[appDelegate.masterViewController presentViewController:extraWebView animated:YES completion:nil];
}
-(BOOL) webView:(WKWebView *)webView decidePolicyForNavigationAction:(NSURLRequest *)request navigationType:(WKNavigationResponsePolicy)navigationType decisionHandler:(nonnull void (^)(WKNavigationActionPolicy))decisionHandler {
if([(AKBannerWebView*)webView isFirstLoad]){
return YES;
}
else{
[self openPopUpWithUrl:[[request URL] absoluteString]];
return NO;
I want to open fullscreen with the wkwebview in the banner? objective-c

GADInterstitialAd not presenting in AppDelegate

Question:(iOS)
i want to display GADInterstitialAd at ApplicationDidBecomeActive in AppDelegate. bellow is the code i'm using
- (void)showInterstitial{
GADRequest *request = [GADRequest request]; // here you need to crate object of GADRequest
request.testDevices = #[ kGADSimulatorID ];
GADInterstitial* interstitialAd = [[GADInterstitial alloc]initWithAdUnitID:AdvertismentID];
interstitialAd.delegate = self;
[interstitialAd loadRequest:request];
}
- (void)interstitialDidReceiveAd:(GADInterstitial *)interstitial {
[interstitial presentFromRootViewController:pagerViewController];
}
- (void)interstitial:(GADInterstitial *)interstitial didFailToReceiveAdWithError:(GADRequestError *)error {
// [[UIApplication sharedApplication] setStatusBarHidden:FALSE withAnimation:NO];
NSLog(#"==%#",[error localizedDescription]);
}
-(void)interstitialWillPresentScreen:(GADInterstitial *)ad{
// [[UIApplication sharedApplication] setStatusBarHidden:TRUE withAnimation:NO];
NSLog(#"on screen");
}
and i'm calling [self showInterstitial] in ApplicationDidBecomeActive i've added <GADInterstitialDelegate> but delegate methods are not calling even i'm not getting errors. please help me.
OK, i got the answer.
simply used strong reference of GADInterstitialAd in above code.

IOS- XMPP - Authenticate and alertview on login button

Currently i am working on XMPP protocol in ios for chatting application. i want to put alert view and authentication on Login button. if authentication will successful then user can see homescreen screen else alert view will appear please check username and password i show chat secure open source project but i can't understand.
//appdelegate.m file .//
- (BOOL)connect
{
if (![xmppStream isDisconnected]) {
return YES;
// isauthenticate=YES;
}
NSString *myJID = [[NSUserDefaults standardUserDefaults] stringForKey:kXMPPmyJID];
NSString *myPassword = [[NSUserDefaults standardUserDefaults] stringForKey:kXMPPmyPassword];
//
// If you don't want to use the Settings view to set the JID,
// uncomment the section below to hard code a JID and password.
//
// myJID = #"user#gmail.com/xmppframework";
// myPassword = #"";
if (myJID == nil || myPassword == nil) {
return NO;
}
[xmppStream setMyJID:[XMPPJID jidWithString:myJID]];
password = myPassword;
NSError *error = nil;
if (![xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error])
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error connecting"
message:#"See console for error details."
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
DDLogError(#"Error connecting: %#", error);
return NO;
}
return YES;
}
- (void)disconnect
{
[self goOffline];
[xmppStream disconnect];
}
#pragma mark UIApplicationDelegate
- (void)applicationDidEnterBackground:(UIApplication *)application
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
#if TARGET_IPHONE_SIMULATOR
DDLogError(#"The iPhone simulator does not process background network traffic. "
#"Inbound traffic is queued until the keepAliveTimeout:handler: fires.");
#endif
if ([application respondsToSelector:#selector(setKeepAliveTimeout:handler:)])
{
[application setKeepAliveTimeout:600 handler:^{
DDLogVerbose(#"KeepAliveHandler");
// Do other keep alive stuff here.
}];
}
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
}
- (void)applicationWillTerminate:(UIApplication *)application
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
[self teardownStream];
}
#pragma mark XMPPStream Delegate
- (void)xmppStream:(XMPPStream *)sender socketDidConnect:(GCDAsyncSocket *)socket
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
}
- (void)xmppStream:(XMPPStream *)sender willSecureWithSettings:(NSMutableDictionary *)settings
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
NSString *expectedCertName = [xmppStream.myJID domain];
if (expectedCertName)
{
settings[(NSString *) kCFStreamSSLPeerName] = expectedCertName;
}
if (customCertEvaluation)
{
settings[GCDAsyncSocketManuallyEvaluateTrust] = #(YES);
}
}
- (void)xmppStream:(XMPPStream *)sender didReceiveTrust:(SecTrustRef)trust
completionHandler:(void (^)(BOOL shouldTrustPeer))completionHandler
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
// The delegate method should likely have code similar to this,
// but will presumably perform some extra security code stuff.
// For example, allowing a specific self-signed certificate that is known to the app.
dispatch_queue_t bgQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(bgQueue, ^{
SecTrustResultType result = kSecTrustResultDeny;
OSStatus status = SecTrustEvaluate(trust, &result);
if (status == noErr && (result == kSecTrustResultProceed || result == kSecTrustResultUnspecified)) {
completionHandler(YES);
}
else {
completionHandler(NO);
}
});
}
- (void)xmppStreamDidSecure:(XMPPStream *)sender
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
}
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
isXmppConnected = YES;
NSError *error = nil;
if (![[self xmppStream] authenticateWithPassword:password error:&error])
{
DDLogError(#"Error authenticating: %#", error);
}
}
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
isauthenticate=YES;
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
[self goOnline];
}
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
}
i have tried with setting BOOL(isauthenticate) in xmppStreamDidAuthenticate method but not success. i can redirect to homepage but if i wrote wrong detail still it will redirect to homepage. i want to set it if username or password are wrong and did not authenticate by server.
//view controller.m file //
#import "ViewController.h"
#import "AppDelegate.h"
#interface ViewController ()<MBProgressHUDDelegate>
{
MBProgressHUD *HUD;
IBOutlet UITextField *mViewEmail;
IBOutlet UITextField *mViewPassword;
}
#end
NSString *const kXMPPmyJID = #"kXMPPmyJID";
NSString *const kXMPPmyPassword = #"kXMPPmyPassword";
#implementation ViewController
- (IBAction)checkLogin:(id)sender {
NSLog(#"Email: %# Password: %#",mViewEmail.text,mViewPassword.text);
[self setField:mViewEmail forKey:kXMPPmyJID];
[self setField:mViewPassword forKey:kXMPPmyPassword];
// if (appdelegate.connect==YES) {
if([ [self appDelegate] connect]) {
// if (appdelegate.isauthenticate==YES) {
HUD = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES] ;
HUD.delegate = self;
HUD.color = [UIColor blackColor];
HUD.labelText = #"Please Wait";
HUD.dimBackground = YES;
// HUD.detailsLabelText = #"Close chat";
[self showHome];
//}
}
//}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Sorry"
message:#"Please Check Username or Password"
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
- (void)showHome{
[self performSegueWithIdentifier:#"signIn" sender:self];
}
ok. so finaly my problem is solved. and i am posting my answer. first of all my mistake is i forgot to write
appdelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
appdelegate.viewController = self; // very imp when you call method in app delegate.h
in my view controller. so when i call viewcontroller's method in appdelegate it call's but do not execute due to above method is missing (Second line). and then i have call view controller's segue method in - (void)xmppStreamDidAuthenticate:(XMPPStream *)sender method. and then work perfectly. so my final solution is
//app delegate.m file//
- (BOOL)connect
{
// Setup HUD(Activity Indicator) when Connect method call //
HUD = [[MBProgressHUD alloc] initWithWindow:[UIApplication sharedApplication].keyWindow]; [self.window.rootViewController.view addSubview:HUD];
[HUD setDetailsLabelText:#"Please wait..."];
[HUD setDimBackground:YES];
[HUD setOpacity:0.5f];
[HUD show:YES];
if (![xmppStream isDisconnected]) {
return YES;
}
NSString *myJID = [[NSUserDefaults standardUserDefaults] stringForKey:kXMPPmyJID];
NSString *myPassword = [[NSUserDefaults standardUserDefaults] stringForKey:kXMPPmyPassword];
if (myJID == nil || myPassword == nil) {
return NO;
}
[xmppStream setMyJID:[XMPPJID jidWithString:myJID]];
password = myPassword;
NSError *error = nil;
if (![xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error])
{
HUD.hidden=YES;
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error connecting"
message:#"See console for error details."
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
DDLogError(#"Error connecting: %#", error);
return NO;
}
return YES;
}
- (void)disconnect
{
[self goOffline];
[xmppStream disconnect];
}
#pragma mark UIApplicationDelegate
- (void)applicationDidEnterBackground:(UIApplication *)application
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
#if TARGET_IPHONE_SIMULATOR
DDLogError(#"The iPhone simulator does not process background network traffic. "
#"Inbound traffic is queued until the keepAliveTimeout:handler: fires.");
#endif
if ([application respondsToSelector:#selector(setKeepAliveTimeout:handler:)])
{
[application setKeepAliveTimeout:600 handler:^{
DDLogVerbose(#"KeepAliveHandler");
// Do other keep alive stuff here.
}];
}
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
}
- (void)applicationWillTerminate:(UIApplication *)application
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
[self teardownStream];
}
#pragma mark XMPPStream Delegate
- (void)xmppStream:(XMPPStream *)sender socketDidConnect:(GCDAsyncSocket *)socket
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
}
- (void)xmppStream:(XMPPStream *)sender willSecureWithSettings:(NSMutableDictionary *)settings
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
NSString *expectedCertName = [xmppStream.myJID domain];
if (expectedCertName)
{
settings[(NSString *) kCFStreamSSLPeerName] = expectedCertName;
}
if (customCertEvaluation)
{
settings[GCDAsyncSocketManuallyEvaluateTrust] = #(YES);
}
}
- (void)xmppStream:(XMPPStream *)sender didReceiveTrust:(SecTrustRef)trust
completionHandler:(void (^)(BOOL shouldTrustPeer))completionHandler
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
dispatch_queue_t bgQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(bgQueue, ^{
SecTrustResultType result = kSecTrustResultDeny;
OSStatus status = SecTrustEvaluate(trust, &result);
if (status == noErr && (result == kSecTrustResultProceed || result == kSecTrustResultUnspecified)) {
completionHandler(YES);
}
else {
completionHandler(NO);
}
});
}
- (void)xmppStreamDidSecure:(XMPPStream *)sender
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
}
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
isXmppConnected = YES;
NSError *error = nil;
if (![[self xmppStream] authenticateWithPassword:password error:&error])
{
DDLogError(#"Error authenticating: %#", error);
}
}
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
HUD.hidden=YES; //Hud Will be hide when User Authenticated
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
[self.viewController showHome]; // view controllers method to go to next view controller //
[self goOnline];
}
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
// HUD will be hidden and alertview will be shown //
HUD.hidden=YES;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Sorry"
message:#"Please Check Username or Password"
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
isauthenticate=NO;
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
{
NSLog(#"error = %#", error);
}
}
and in viewcontroller.m we have show that viewcontroller is also appdelegate controller. so we have to declare it in - (void)viewDidLoad method.
// viewcontroller.m file//
- (void)viewDidLoad
{
[super viewDidLoad];
appdelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
appdelegate.viewController = self;
}
- (AppDelegate *)appDelegate
{
return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}
- (IBAction)checkLogin:(id)sender {
[self dismissKeyboard];
NSLog(#"Email: %# Password: %#",mViewEmail.text,mViewPassword.text);
[self setField:mViewEmail forKey:kXMPPmyJID];
[self setField:mViewPassword forKey:kXMPPmyPassword];
[[self appDelegate ]connect];//call when loginbutton pressed
}
//call in appdelegate.h // segue(push) to next view
- (void)showHome
{
[self performSegueWithIdentifier:#"signIn" sender:self];
}
Note: I have tried to explain as much as i can.
If username and password are correct then xmppStreamDidAuthenticate method call and if one of them is incorrect then didNotAuthenticate method call.
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
}
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
NSLog(#"error = %#", error);
}
Here print error and display this error in UIALertview as you required.
Actually you are checking XMPP connection that is not means Authenticate User. if your User Name and password is correct then you received response in xmppStreamDidAuthenticate method. where you can write the code to push to HomeViewController once user is verified.
Below two methods, you can used to show alert or push to another view once user varified.
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
}
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
NSLog(#"Error");
}
this is XMPP Delegate methods
Hope this help you.

IOS Google admob appdelegate code is deprecated for splash interstitial

I am using IOS Google Admob SDK 6.11.1 and Xcode 5.1.
If I thought loadrequest is replacement for loadanddisplayrequest but its not.
[splashInterstitial_ loadRequest:[GADRequest request]];
Because intertitial never appears by using loadrequest only.
loadAndDisplayRequest this method is working but I want to know whats the replacement for this deprecated method.
You need to call presentFromRootViewController: after you've received the interstitial:
#pragma mark - GADInterstitialDelegate
- (void)interstitialDidReceiveAd:(DFPInterstitial *)ad
{
[splashInterstitial_ presentFromRootViewController:self];
}
Use this code in appdelegate .it's working for me.
- (void)applicationDidBecomeActive:(UIApplication *)application
{
GADRequest *request = [GADRequest request]; // here you need to crate object of GADRequest
interstitial_ = [[GADInterstitial alloc] init];
interstitial_.adUnitID =#"ca-app-pub-43434/343434";
interstitial_.delegate = self;
// request.testDevices = [NSArray arrayWithObjects:
// #"MY_SIMULATOR_IDENTIFIER",
// #"fbb99fa8c725017137fb191a20aa342491b82a37",
// nil];
[interstitial_ loadRequest:request];
}
- (void)interstitial:(GADInterstitial *)interstitial
didFailToReceiveAdWithError:(GADRequestError *)error {
NSLog(#"==%#",[error localizedDescription]);
}
-(void)interstitialWillPresentScreen:(GADInterstitial *)ad{
NSLog(#"on screen");
}
- (void)interstitialDidReceiveAd:(GADInterstitial *)interstitial {
// [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
[interstitial presentFromRootViewController:self.window.rootViewController];
// [interstitial presentFromRootViewController:self];
}

Update ProgressView after the view controller has been changed

I currently have a progress view which shows the current amount of how much of a file has been downloaded so far. When the user clicks the download button the progress succesfully updates and when they leave the view controller and return to it while it is still downloading the progress still updates successfuly. However my problem is when the download finishes and the user has left and returned to the view the progress view no longer responds to any updates. I have did some research into multi-threading and seen that many people suggest to do any UI updates in the main thread like so:
[self performSelectorOnMainThread:#selector(progressUpdate) withObject:nil waitUntilDone:NO];
So I tried it in my code and the still got the same results (once the user leaves and returns to the view controller after the download has finished the progress view does not respond to any updates). I then added a NSLog to see if the method was being called and the debugger outputted the NSLog. So what is going on? Here is the code for the view controller:
VideoTest.m
#import "VideoTest.h"
#import "AppDelegate.h"
#import "FileDownloadInfo.h"
#interface VideoTest ()
#property (nonatomic, strong) NSURLSession *session;
#property (nonatomic, strong) NSMutableArray *arrFileDownloadData;
#property (nonatomic, strong) NSURL *docDirectoryURL;
-(void)initializeFileDownloadDataArray;
-(int)getFileDownloadInfoIndexWithTaskIdentifier:(unsigned long)taskIdentifier;
#end
#implementation VideoTest{
NSString *url;
}
#synthesize moviePlayer;
#synthesize download;
#synthesize videoAlreadyPlaying, progressView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//Setting video URl
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
url = #"http://therosary.info/AppVideos/TheChaplet/Information%20on%20Divine%20Mercy.mp4";
//selectors set
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(MPMoviePlayerPlaybackStateDidChange:)
name:MPMoviePlayerPlaybackStateDidChangeNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(willEnterFullscreen:) name:MPMoviePlayerWillEnterFullscreenNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(willExitFullscreen:) name:MPMoviePlayerWillExitFullscreenNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(enteredFullscreen:) name:MPMoviePlayerDidEnterFullscreenNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(exitedFullscreen:) name:MPMoviePlayerDidExitFullscreenNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(playbackFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
//Play the movie
videoAlreadyPlaying=#"TRUE";
self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:url]];
[self.view addSubview:moviePlayer.view];
self.moviePlayer.view.frame = CGRectMake(0,64,320,220);
[moviePlayer play];
[self initializeFileDownloadDataArray];
NSArray *URLs = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
self.docDirectoryURL = [URLs objectAtIndex:0];
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfiguration:#"com.jjdoherty98.Marion_s_Net"];
sessionConfiguration.HTTPMaximumConnectionsPerHost = 5;
self.session = [NSURLSession sessionWithConfiguration:sessionConfiguration
delegate:self
delegateQueue:nil];
if([appDelegate.isAlreadyDownloading isEqual:#"FALSE"] || appDelegate.isAlreadyDownloading==nil){
self.progressView.hidden = YES;
progressView.progress=0;
}
if([appDelegate.isAlreadyDownloading isEqual:#"TRUE"]){
[self performSelectorOnMainThread:#selector(progressUpdate) withObject:nil waitUntilDone:NO];
}
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if (self.isMovingFromParentViewController || self.isBeingDismissed) {
NSLog(#"Left View");
[moviePlayer stop];
}
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationPortrait | UIInterfaceOrientationPortraitUpsideDown;
}
- (BOOL)shouldAutorotate{
AppDelegate *mainDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
mainDelegate.fullScreenVideoIsPlaying = #"TRUE";
return YES;
}
- (void)MPMoviePlayerPlaybackStateDidChange:(NSNotification *)notification
{
if (moviePlayer.playbackState == MPMoviePlaybackStatePlaying)
{ //playing
videoAlreadyPlaying = #"TRUE";
}
if (moviePlayer.playbackState == MPMoviePlaybackStateStopped)
{ //stopped
}if (moviePlayer.playbackState == MPMoviePlaybackStatePaused)
{ //paused
}if (moviePlayer.playbackState == MPMoviePlaybackStateInterrupted)
{ //interrupted
}if (moviePlayer.playbackState == MPMoviePlaybackStateSeekingForward)
{ //seeking forward
}if (moviePlayer.playbackState == MPMoviePlaybackStateSeekingBackward)
{ //seeking backward
}
}
- (void)willEnterFullscreen:(NSNotification*)notification {
NSLog(#"willEnterFullscreen");
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
appDelegate.fullScreenVideoIsPlaying = #"TRUE";
}
- (void)enteredFullscreen:(NSNotification*)notification {
NSLog(#"enteredFullscreen");
}
- (void)willExitFullscreen:(NSNotification*)notification {
NSLog(#"willExitFullscreen");
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
appDelegate.fullScreenVideoIsPlaying = #"FALSE";
}
- (void)exitedFullscreen:(NSNotification*)notification {
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
NSLog(#"exitedFullscreen");
if(appDelegate.CurrentProgress==0){
progressView.hidden=TRUE;
}else{
[self performSelectorOnMainThread:#selector(progressUpdate) withObject:nil waitUntilDone:NO];
}
}
- (void)playbackFinished:(NSNotification*)notification {
NSNumber* reason = [[notification userInfo] objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
switch ([reason intValue]) {
case MPMovieFinishReasonPlaybackEnded:
NSLog(#"playbackFinished. Reason: Playback Ended");
videoAlreadyPlaying=#"FALSE";
[moviePlayer stop];
[moviePlayer play];
break;
case MPMovieFinishReasonPlaybackError:
NSLog(#"playbackFinished. Reason: Playback Error");
videoAlreadyPlaying=#"FALSE";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Video Failed To Load!"
message:#"Unable to connect to server, please try again later!"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
break;
case MPMovieFinishReasonUserExited:
NSLog(#"playbackFinished. Reason: User Exited");
videoAlreadyPlaying=#"FALSE";
break;
default:
break;
}
[self.moviePlayer setFullscreen:NO animated:YES];
}
-(IBAction)buttonPressed:(id)sender{
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
if([appDelegate.isThereInternet isEqual:#"TRUE"]){
if([appDelegate.isAlreadyDownloading isEqual: #"FALSE"]){
//If there is internet and not already downloading
progressView.hidden=FALSE;
progressView.progress=0;
FileDownloadInfo *fdi = [self.arrFileDownloadData objectAtIndex:0];
fdi.downloadTask = [self.session downloadTaskWithURL:[NSURL URLWithString:fdi.downloadSource]];
fdi.taskIdentifier = fdi.downloadTask.taskIdentifier;
// Start the task.
[fdi.downloadTask resume];
}}
if ([appDelegate.isThereInternet isEqual:#"FALSE"]) {
//No internet available
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Unable to connect to server"
message:#"Internet connection appears to be offline, please try again later!"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
if([appDelegate.isAlreadyDownloading isEqual:#"TRUE"]){
//Is already downloaing
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"File Already Downloading"
message:#"Multiple files can not be downloaded at the same time!"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
}
-(void)initializeFileDownloadDataArray{
self.arrFileDownloadData = [[NSMutableArray alloc] init];
[self.arrFileDownloadData addObject:[[FileDownloadInfo alloc] initWithFileTitle:nil andDownloadSource:url]];
}
-(int)getFileDownloadInfoIndexWithTaskIdentifier:(unsigned long)taskIdentifier{
int index = 0;
for (int i=0; i<[self.arrFileDownloadData count]; i++) {
FileDownloadInfo *fdi = [self.arrFileDownloadData objectAtIndex:i];
if (fdi.taskIdentifier == taskIdentifier) {
index = i;
break;
}
}
return index;
}
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *destinationFilename = downloadTask.originalRequest.URL.lastPathComponent;
NSURL *destinationURL = [self.docDirectoryURL URLByAppendingPathComponent:destinationFilename];
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
if ([fileManager fileExistsAtPath:[destinationURL path]]) {
[fileManager removeItemAtURL:destinationURL error:nil];
}
BOOL success = [fileManager copyItemAtURL:location
toURL:destinationURL
error:&error];
if (success) {
int index = [self getFileDownloadInfoIndexWithTaskIdentifier:downloadTask.taskIdentifier];
FileDownloadInfo *fdi = [self.arrFileDownloadData objectAtIndex:index];
fdi.isDownloading = NO;
fdi.downloadComplete = YES;
// Set the initial value to the taskIdentifier property of the fdi object,
// so when the start button gets tapped again to start over the file download.
fdi.taskIdentifier = -1;
// In case there is any resume data stored in the fdi object, just make it nil.
fdi.taskResumeData = nil;
}
else{
NSLog(#"Unable to copy temp file. Error: %#", [error localizedDescription]);
}
}
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
if (error != nil) {
NSLog(#"Download completed with error: %#", [error localizedDescription]);
appDelegate.isAlreadyDownloading=#"FALSE";
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Failed to download!"
message:#"Unable to connect to the server!"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
});
}
else{
appDelegate.isAlreadyDownloading=#"FALSE";
NSLog(#"Download finished successfully.");
dispatch_async(dispatch_get_main_queue(), ^{
FileDownloadInfo *fdi = [self.arrFileDownloadData objectAtIndex:0];
fdi.isDownloading = NO;
fdi.downloadComplete = YES;
fdi.taskIdentifier = -1;
fdi.taskResumeData = nil;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Download Complete!"
message:#"Go to downloads section to view the file now!"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
});
}
}
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
if (totalBytesExpectedToWrite == NSURLSessionTransferSizeUnknown) {
NSLog(#"Unknown transfer size");
}
else{
int index = [self getFileDownloadInfoIndexWithTaskIdentifier:downloadTask.taskIdentifier];
FileDownloadInfo *fdi = [self.arrFileDownloadData objectAtIndex:index];
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
appDelegate.isAlreadyDownloading=#"TRUE";
fdi.downloadProgress = (double)totalBytesWritten / (double)totalBytesExpectedToWrite;
appDelegate.CurrentProgress = fdi.downloadProgress;
[self performSelectorOnMainThread:#selector(progressUpdate) withObject:nil waitUntilDone:NO];
}
}
-(void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session{
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
[self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
if ([downloadTasks count] == 0) {
if (appDelegate.backgroundTransferCompletionHandler != nil) {
// Make nil the backgroundTransferCompletionHandler.
appDelegate.backgroundTransferCompletionHandler = nil;
progressView.hidden=TRUE;
// Show a local notification when all downloads are over.
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.alertBody = #"All files have been downloaded!";
[[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
}
}
}];
}
-(void)progressUpdate{
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
if ([appDelegate.isAlreadyDownloading isEqual:#"TRUE"]) {
progressView.progress = appDelegate.CurrentProgress;
[NSTimer scheduledTimerWithTimeInterval:0 target:self selector:#selector(progressUpdate) userInfo:nil repeats:NO];
NSLog(#"Is this method being called");
if (appDelegate.CurrentProgress==1) {
progressView.hidden=TRUE;
}
}
}
#end
Any help would be appreciated!

Resources