judaco / iPhone

0 stars 0 forks source link

iPhone - Class 12 #8

Open judaco opened 7 years ago

judaco commented 7 years ago
//
//  AppDelegate.h
//  Background Fetch
//
//  Created by hackeru on 21/05/2017.
//  Copyright © 2017 juda. All rights reserved.
//

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

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property int nouvelle;

-(NSMutableArray<NewsItem*> *) getNews;

@end
judaco commented 7 years ago
//
//  AppDelegate.m
//  Background Fetch
//
//  Created by hackeru on 21/05/2017.
//  Copyright © 2017 juda. All rights reserved.
//

#import "AppDelegate.h"
#import "NewsItem.h"

@implementation AppDelegate
{
    NSMutableArray<NewsItem *> * newsItems;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    newsItems = [NSMutableArray arrayWithObject:[[NewsItem alloc] initWithDate:[NSDate date] andContent:@"News item 1"]];
    [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];

    //dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (NSEC_PER_SEC * 10);
    //dispatch_after(popTime, dispatch_get_main_queue(), ^{
        //NSNotification * notification = [NSNotification notificationWithName:@"notification1" object:nil];
        //[NSNotificationCenter defaultCenter] postnotif
    //});

    return YES;
}

-(NSMutableArray<NewsItem *> *)getNews{
    return newsItems;
}

-(BOOL)fetchNewsItem{
    NewsItem * newsItem = [[NewsItem alloc] initWithDate:[NSDate date] andContent:[NSString stringWithFormat:@"News item 1 %lu", newsItems.count+1]];
    [newsItems addObject:newsItem];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"newNewsItem" object:nil];
    return YES;
}
-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{

    if ([self fetchNewsItem]) {
        completionHandler(UIBackgroundFetchResultNewData);
    }else{
        completionHandler(UIBackgroundFetchResultNoData);
    }

}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"broughtToForeground" object:nil];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
judaco commented 7 years ago
//
//  NewsItem.h
//  Background Fetch
//
//  Created by hackeru on 21/05/2017.
//  Copyright © 2017 juda. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface NewsItem : NSObject

@property NSDate * date;
@property NSString * content;

-(instancetype)initWithDate:(NSDate*)date andContent:(NSString*) content;

@end
judaco commented 7 years ago
//
//  NewsItem.m
//  Background Fetch
//
//  Created by hackeru on 21/05/2017.
//  Copyright © 2017 juda. All rights reserved.
//

#import "NewsItem.h"

@implementation NewsItem

@synthesize date, content;
-(instancetype)initWithDate:(NSDate*)date andContent:(NSString*)content{
    self = [super init];
    if (self != nil) {
        self.date = date;
        self.content = content;
    }
    return self;
}

@end
judaco commented 7 years ago
//
//  ViewController.h
//  Background Fetch
//
//  Created by hackeru on 21/05/2017.
//  Copyright © 2017 juda. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@end

-------

//
//  ViewController.m
//  Background Fetch
//
//  Created by hackeru on 21/05/2017.
//  Copyright © 2017 juda. All rights reserved.
//

#import "ViewController.h"
#import "AppDelegate.h"
#import "NewsItem.h"

@implementation ViewController
{
    BOOL mustReloadData;
    NSMutableArray<NewsItem *> * newsItems;
    UITableView * tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    mustReloadData = NO;

    AppDelegate * appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    newsItems = [appDelegate getNews];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:NSSelectorFromString(@"handleNewNewsItem:") name:@"newNewsItem" object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:NSSelectorFromString(@"handleBroughtToForeground:") name:@"broughtToForeground" object:nil];

}
-(void)handleNewNewsItem:(NSNotification*)sender{
    NSLog(@"new news item");
    if([self isBeingPresented]){
        [tableView reloadData];
    }else{
        mustReloadData = YES;
    }
}

-(void)handleBroughtToForground:(NSNotification*)sender{
    NSLog(@"brought to foreground");
    if(mustReloadData){
        [tableView reloadData];
        mustReloadData = NO;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
judaco commented 7 years ago
//
//  AppDelegate.h
//  Audio in the Background
//
//  Created by hackeru on 24/05/2017.
//  Copyright © 2017 juda. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end

-----------

//
//  AppDelegate.m
//  Audio in the Background
//
//  Created by hackeru on 24/05/2017.
//  Copyright © 2017 juda. All rights reserved.
//

#import "AppDelegate.h"
#import <AVFoundation/AVFoundation.h>

@interface AppDelegate () <AVAudioPlayerDelegate>

@end

@implementation AppDelegate
{
    AVAudioPlayer * audioPlayer;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    //closure = what I want that will happen
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[NSNotificationCenter defaultCenter] addObserver:self selector:NSSelectorFromString(@"handleInterruption:") name:AVAudioSessionInterruptionNotification object:nil];
        AVAudioSession* audioSession = [AVAudioSession sharedInstance];
        NSError * error;
        //I got the address of error and can change is var
        [audioSession setActive:YES error:&error];

        if (error != nil) {
            //STOP
        }
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:&error];
        if (error != nil) {
            //STOP
        }
        NSString * filePath = [[NSBundle mainBundle] pathForResource:@"Developers" ofType:@"mp3"];
        NSData * fileData = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:&error];
        if (error != nil) {
            //STOP
        }
        audioPlayer = [[AVAudioPlayer  alloc] initWithData:fileData fileTypeHint:@"mp3" error:&error];
        if (error != nil) {
            //STOP
        }
        audioPlayer.delegate = self;
        if([audioPlayer prepareToPlay] && [audioPlayer play]){
            //now audio is playing
        }

    });
    return YES;
}

-(void)handleInterruption:(NSNotification*)notification{

}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
judaco commented 7 years ago
//
//  AppDelegate.h
//  Handling Location Changes in the Background
//
//  Created by hackeru on 24/05/2017.
//  Copyright © 2017 juda. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end

------------

//
//  AppDelegate.m
//  Handling Location Changes in the Background
//
//  Created by hackeru on 24/05/2017.
//  Copyright © 2017 juda. All rights reserved.
//

#import "AppDelegate.h"
#import <CoreLocation/CoreLocation.h>

@interface AppDelegate () <CLLocationManagerDelegate>

@end

@implementation AppDelegate
{
    CLLocationManager * locationManager;
    BOOL isInBackground;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    locationManager = [[CLLocationManager alloc] init];
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.delegate = self;
    [locationManager startUpdatingLocation];

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    isInBackground = YES;
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
}
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    switch (<#expression#>) {
        case <#constant#>:
            <#statements#>
            break;

        default:
            break;
    }
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    isInBackground = NO;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    if (isInBackground) {
        //do NOT do heavy stuff, don't do UI stuff, less using of battery
    }else{
        //go crazy and do heavy stuff
    }
    if(locations.count > 0){
    NSLog(@"%li%f %f", locations.count, locations[0].coordinate.latitude, locations[0].coordinate.longitude);
    }else{
        NSLog(@"empty");
    }

}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end