Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // ViewController.m
- // newsstand
- //
- // Created by joao vitor on 02/05/13.
- // Copyright (c) 2013 joao vitor. All rights reserved.
- //
- #import "ViewController.h"
- #import "CustomCell.h"
- #import "Publisher.h"
- #import "ReceiptCheck.h"
- #import "InAppViewController.h"
- #include <unistd.h>
- #include "JsonPost.h"
- #include "Reachability.h"
- @interface ViewController ()
- @property (nonatomic, strong) NSOperationQueue *thumbnailQueue;
- -(void)showIssues;
- -(void)loadIssues;
- -(void)readIssue:(NKIssue *)nkIssue;
- -(void)downloadIssueAtIndex:(NSInteger)index;
- -(void)errorWithTransaction:(SKPaymentTransaction *)transaction;
- -(void)finishedTransaction:(SKPaymentTransaction *)transaction;
- -(void)checkReceipt:(NSData *)receipt;
- - (NSString *)decodeBase64:(NSString *)input;
- - (void) interactWithUIAction;
- @end
- @implementation ViewController
- @synthesize purchasing=purchasing_;
- Publisher *publisher;
- NSArray *issues;
- CustomCell *lastCellSelected;
- CustomCell *currentDownloadCell;
- bool downloadInProgress = FALSE;
- int interactVar = 0;
- NSTimer *timer;
- NSMutableSet *indexPathsNeedingImages;
- NSIndexPath *lastCellIndex;
- NSIndexPath *currentDownloadIndex;
- BOOL refresh;
- BOOL haveNet;
- BOOL restuaro;
- - (void)viewDidLoad
- {
- restuaro = true;
- refresh = true;
- _pleaseWaitWindow.hidden = false;
- [super viewDidLoad];
- buttonsArray = [[NSMutableArray alloc] init];
- if([publisher isReady]) {
- [self showIssues];
- } else {
- [self loadIssues];
- }
- [self Reachability];
- [[self myCollectionView] setDataSource:self];
- [[self myCollectionView] setDelegate:self];
- // Notificacoes de sistema...
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reload) name:IAPHelperProductPurchasedNotification object:nil];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshLogin) name:DismissPopoverNotification object:nil];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(interactWithUI) name:@"interactWithUI" object:nil];
- [[NSNotificationCenter defaultCenter] addObserver:self
- selector:@selector(forceUpdate)
- name:@"appDidBecomeActive"
- object:nil];
- [[NSUserDefaults standardUserDefaults] synchronize];
- [self performSelector:@selector(startBanner) withObject:nil afterDelay:2.0];
- }
- -(void)viewDidAppear:(BOOL)animated{
- refresh = true;
- }
- -(void)forceUpdate{
- [self loadIssues];
- }
- - (void)viewWillAppear:(BOOL)animated{
- issuesBuyit = [[NSMutableArray alloc] init];
- NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
- issuesBuyit = [[defaults objectForKey:@"issuesBuyit"] mutableCopy];
- }
- -(void)startBanner{
- @try {
- [[JsonPost shareGlobalData] postMessageGetBanner];
- [self performSelectorInBackground:@selector(SetBanner) withObject:nil];
- }
- @catch (NSException *exception) {
- NSLog(@"Banner no fundo crashou.");
- }
- }
- - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
- {
- self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
- if (self) {
- // Custom initialization
- publisher = [[Publisher alloc] init];
- }
- return self;
- }
- - (void)didReceiveMemoryWarning
- {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- #pragma mark - Issue actions
- -(void)readIssue:(NKIssue *)nkIssue {
- //--
- [[NKLibrary sharedLibrary] setCurrentlyReadingIssue:nkIssue];
- NSString *phrase = nil; // Document password (for unlocking most encrypted PDF files)
- ReaderDocument *document = [ReaderDocument withDocumentFilePath:[publisher downloadPathForIssue:nkIssue] password:phrase];
- if (document != nil) // Must have a valid ReaderDocument object in order to proceed with things
- {
- ReaderViewController *readerViewController = [[ReaderViewController alloc] initWithReaderDocument:document];
- readerViewController.delegate = self; // Set the ReaderViewController delegate to self
- #if (DEMO_VIEW_CONTROLLER_PUSH == TRUE)
- [self.navigationController pushViewController:readerViewController animated:YES];
- #else // present in a modal view controller
- readerViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
- readerViewController.modalPresentationStyle = UIModalPresentationFullScreen;
- [self presentModalViewController:readerViewController animated:YES];
- #endif // DEMO_VIEW_CONTROLLER_PUSH
- }
- }
- - (void)dismissReaderViewController:(ReaderViewController *)viewController {
- // [self dismissModalViewControllerAnimated:YES];
- [self dismissViewControllerAnimated:YES completion:nil];
- }
- -(void)downloadIssueAtIndex:(NSInteger)index {
- NKLibrary *nkLib = [NKLibrary sharedLibrary];
- NKIssue *nkIssue = [nkLib issueWithName:[publisher nameOfIssueAtIndex:index]];
- NSURL *downloadURL = [publisher contentURLForIssueWithName:nkIssue.name];
- if(!downloadURL) return;
- NSURLRequest *req = [NSURLRequest requestWithURL:downloadURL];
- NKAssetDownload *assetDownload = [nkIssue addAssetWithRequest:req];
- [assetDownload downloadWithDelegate:self];
- [assetDownload setUserInfo:[NSDictionary dictionaryWithObjectsAndKeys:
- [NSNumber numberWithInt:index],@"Index",
- nil]];
- downloadInProgress = TRUE;
- dispatch_queue_t queue = dispatch_queue_create("pt.diariocoimbra.newsstand.bgqueue", NULL);
- dispatch_async(queue, ^{
- /* put the codes which makes UI unresponsive like reading from network*/
- dispatch_async(dispatch_get_main_queue(), ^{
- /* do the UI related work on main thread */
- _globalProgressBar.progress = 0;
- _globalProgressBar.hidden = FALSE;
- _globalPercentDownload.hidden = FALSE;
- //[_myCollectionView reloadData]; -------
- NSLog(@"Download starting (Updating UI now)...");
- });
- });
- }
- #pragma mark - NSURLConnectionDownloadDelegate
- -(void)updateProgressOfConnection:(NSURLConnection *)connection withTotalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long)expectedTotalBytes
- {
- float current_value = 1.f*totalBytesWritten/expectedTotalBytes;
- _globalProgressBar.progress = current_value;
- NSString *strFromInt = [NSString stringWithFormat:@"%3.0f%@", (current_value*100), @"\%"];
- [_globalPercentDownload setText:strFromInt];
- }
- -(void)connection:(NSURLConnection *)connection didWriteData:(long long)bytesWritten totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long)expectedTotalBytes {
- [self updateProgressOfConnection:connection withTotalBytesWritten:totalBytesWritten expectedTotalBytes:expectedTotalBytes];
- }
- -(void)connectionDidResumeDownloading:(NSURLConnection *)connection totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long)expectedTotalBytes {
- [self updateProgressOfConnection:connection withTotalBytesWritten:totalBytesWritten expectedTotalBytes:expectedTotalBytes];
- }
- // O download terminou com sucesso ...
- -(void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL
- {
- currentDownloadCell = (CustomCell *)[_myCollectionView cellForItemAtIndexPath:currentDownloadIndex];
- //nova linha alterada
- // copy file to destination URL
- NKAssetDownload *dnl = connection.newsstandAssetDownload;
- NKIssue *nkIssue = dnl.issue;
- NSString *contentPath = [publisher downloadPathForIssue:nkIssue];
- NSError *moveError=nil;
- if([[NSFileManager defaultManager] moveItemAtPath:[destinationURL path] toPath:contentPath error:&moveError]==NO) {
- NSLog(@"Error copying file from %@ to %@",destinationURL,contentPath);
- }
- // update the Newsstand icon
- UIImage *img = [publisher coverImageForIssue:nkIssue];
- if(img) {
- [[UIApplication sharedApplication] setNewsstandIconImage:img];
- [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
- }
- // [self showIssues];
- // interactVar = 4;
- // [[NSNotificationCenter defaultCenter] postNotificationName:@"interactWithUI" object:nil userInfo:nil];
- downloadInProgress = FALSE;
- dispatch_queue_t queue = dispatch_queue_create("pt.diariocoimbra.newsstand.bgqueue", NULL);
- dispatch_async(queue, ^{
- /* put the codes which makes UI unresponsive like reading from network*/
- dispatch_async(dispatch_get_main_queue(), ^{
- /* do the UI related work on main thread */
- _globalProgressBar.hidden = true;
- _globalPercentDownload.hidden = true;
- currentDownloadCell.btPrice.titleLabel.text = Downloaded;
- _pleaseWaitWindow.hidden = true;
- // [_myCollectionView reloadData];
- NSLog(@"Download sucsess (Updating UI now)...");
- });
- });
- //[_myCollectionView reloadInputViews];
- }
- #pragma mark - Publisher interaction
- -(void)loadIssues {
- NSLog(@"Tou aqui");
- NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(publisherReady:) name:PublisherDidUpdateNotification object:publisher];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(publisherFailed:) name:PublisherFailedUpdateNotification object:publisher];
- [publisher getIssuesList];
- }
- -(void)publisherReady:(NSNotification *)not {
- [[NSNotificationCenter defaultCenter] removeObserver:self name:PublisherDidUpdateNotification object:publisher];
- [[NSNotificationCenter defaultCenter] removeObserver:self name:PublisherFailedUpdateNotification object:publisher];
- [self showIssues];
- }
- -(void)showIssues {
- NSLog(@"Show issues...");
- if (refresh) {
- [buttonsArray removeAllObjects];
- [_myCollectionView reloadData];
- [_myCollectionView reloadInputViews];
- }
- refresh = false;
- }
- -(void)publisherFailed:(NSNotification *)not {
- [[NSNotificationCenter defaultCenter] removeObserver:self name:PublisherDidUpdateNotification object:publisher];
- [[NSNotificationCenter defaultCenter] removeObserver:self name:PublisherFailedUpdateNotification object:publisher];
- // NSLog(@"%@",not);
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Erro"
- message:@"Verifique a sua ligação"
- delegate:nil
- cancelButtonTitle:@"Close"
- otherButtonTitles:nil];
- [alert show];
- }
- #pragma mark - Collection
- // Uma coleccao de edicoes (o grupo das 15)
- - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
- return 1;
- }
- // Numero de edicoes que vao ser carregadas
- - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
- NSLog(@"[SL] numberOfItemsInSection = %d", [publisher numberOfIssues]);
- return [publisher numberOfIssues];
- }
- - (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
- [indexPathsNeedingImages removeObject:indexPath];
- // NSLog(@"[SL] Removing hidden Cell # %d", indexPath.row);
- }
- -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
- {
- // PQP
- CustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
- NSInteger index = indexPath.item;
- // NSLog(@"[SL] Loading Cell | indexPath.row = %d / item = %ld / Label = %@ / Total = %d", indexPath.row, indexPath.item, cell.lblDesc.text, itemCount);
- /* for (int i = 0; i < 15 ; i++)
- NSLog(@"[SL] data at # %d : Name = %@", i, [publisher nameOfIssueAtIndex:i]);*/
- //if ([cell.lblDesc.text isEqualToString:@"Label"])
- {
- NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
- [[cell lblDesc] setText:[publisher titleOfIssueAtIndex:index]];
- // NSString *strFromInt = [NSString stringWithFormat:@"%@%@%@", [publisher titleOfIssueAtIndex:index], @" ", [NSString stringWithFormat:@"%d", index]];
- // [[cell lblDesc] setText:strFromInt];
- NKLibrary *nkLib = [NKLibrary sharedLibrary];
- NKIssue *nkIssue = [nkLib issueWithName:[publisher nameOfIssueAtIndex:index]];
- [publisher setCoverOfIssueAtIndex:index completionBlock:^(UIImage *img) {
- [self performSelectorOnMainThread:@selector(threadForImage:) withObject:[NSArray arrayWithObjects:cell,img, nil] waitUntilDone:NO];
- }];
- //checkReceipts -> verifica Individual
- //dateBetweenDates -> data forçada
- // NSLog(@"[SL] ViewController.m : cellForItemAtIndexPath : data_inicio = %@",[prefs objectForKey:@"data_inicio"]);
- // NSLog(@"[SL] ViewController.m : cellForItemAtIndexPath : dateofIssueAtIndex = %@", [publisher dateOfIssueAtIndex:index]);
- // NSLog(@"[SL] ViewController.m : cellForItemAtIndexPath : bundleofIssue = %@", [publisher bundleOfIssueAtIndex:index]);
- // NSLog(@"[SL] ViewController.m : cellForItemAtIndexPath : checkReceipts = %d", [self checkReceipts:[publisher dateOfIssueAtIndex:index]]);
- /*
- CustomCell *aux= (CustomCell *)[_myCollectionView cellForItemAtIndexPath:currentDownloadIndex];
- NSLog(@"Download %@",currentDownloadCell.lblDesc.text);
- NSLog(@" Carregado %@",[publisher titleOfIssueAtIndex:index]);
- NSLog(@" Index %ld",(long)currentDownloadIndex.row);
- if ([[[aux lblDesc] text] isEqualToString:[publisher titleOfIssueAtIndex:index]])
- {
- [[cell btPrice] setTitle: @"Aguarde" forState:UIControlStateNormal];
- }
- else
- {*/
- if([self checkReceipts:[publisher dateOfIssueAtIndex:index]] == 1 || // Se subscricao Apple Activa
- ([self dateBetweenDates:[publisher dateOfIssueAtIndex:index]] == true && [prefs objectForKey:@"data_inicio"]!=nil) // ... ou se Subscricao Nao Apple Activa
- ){
- if(nkIssue.status == NKIssueContentStatusAvailable)
- [cell.btPrice setTitle:Downloaded forState:UIControlStateNormal];
- else
- [cell.btPrice setTitle:Subscribed forState:UIControlStateNormal];
- }
- else
- { // Caso nao exista nenhuma das subscricoes activas (apple ou nao apple)
- if([self checkBundleList:[publisher bundleOfIssueAtIndex:index]] == 0) // se nao existe uma compra apple individual comprada
- [cell.btPrice setTitle:[publisher priceOfIssueAtIndex:index] forState:UIControlStateNormal];
- else{
- if(nkIssue.status==NKIssueContentStatusAvailable)
- [cell.btPrice setTitle:Downloaded forState:UIControlStateNormal];
- else
- [cell.btPrice setTitle:Payed forState:UIControlStateNormal];
- }
- }
- // }
- [buttonsArray addObject:cell.btPrice.titleLabel.text];
- }
- return cell;
- }
- -(void)threadForImage:(NSArray*)array{
- NSLog(@"A buscar imagem...");
- CustomCell *cell = [array objectAtIndex:0];
- UIImage *img = [array objectAtIndex:1];
- // lastCell.image.image = img;
- cell.image.image = img;
- }
- - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
- @try {
- lastCellSelected = (CustomCell *)[collectionView cellForItemAtIndexPath:indexPath];
- lastCellIndex = indexPath;
- NSString *aux = lastCellSelected.btPrice.titleLabel.text;
- NSLog(@"[SL] Pressionei %ld", (long)indexPath.row);
- if(![aux isEqualToString:Subscribed] &&
- ![aux isEqualToString:Payed] &&
- ![aux isEqualToString:Wait] &&
- ![aux isEqualToString:Downloaded])
- {
- if(!haveNet){
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Modo Offline" message:@"Necessita de internet para fazer uma compra" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
- [alert show];
- return;
- }
- [self performSelectorOnMainThread:@selector(startAnimate) withObject:nil waitUntilDone:YES];
- dispatch_queue_t queue = dispatch_queue_create("pt.diariocoimbra.newsstand.bgqueue", NULL);
- dispatch_async(queue, ^{
- /* put the codes which makes UI unresponsive like reading from network*/
- dispatch_async(dispatch_get_main_queue(), ^{
- /* do the UI related work on main thread */
- _pleaseWaitWindow.hidden = false;
- // [_myCollectionView reloadData]; ----------
- NSLog(@"Buying started (Updating UI now)...");
- });
- });
- [self paymentStart:[publisher bundleOfIssueAtIndex:indexPath.row]];
- }
- else
- {
- NKLibrary *nkLib = [NKLibrary sharedLibrary];
- NKIssue *nkIssue = [nkLib issueWithName:[publisher nameOfIssueAtIndex:indexPath.row]];
- if(nkIssue.status==NKIssueContentStatusAvailable) {
- [self readIssue:nkIssue];
- } else if(nkIssue.status==NKIssueContentStatusNone) {
- if(!haveNet){
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Modo Offline" message:@"Necessita de internet para descarregar esta edição" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
- [alert show];
- return;
- }
- // Download em progresso: Não permito outras interaccoes com a grelha de edicoes
- if (downloadInProgress)
- {
- _globalProgressBar.hidden = FALSE;
- _globalPercentDownload.hidden = FALSE;
- return;
- }
- currentDownloadCell = (CustomCell *)[collectionView cellForItemAtIndexPath:indexPath];
- currentDownloadIndex = indexPath;
- // interactVar = 3;
- // [[NSNotificationCenter defaultCenter] postNotificationName:@"interactWithUI" object:nil userInfo:nil];
- // [[NSNotificationCenter defaultCenter] postNotificationName:@"interactWithUI" object:nil userInfo:nil];
- downloadInProgress = TRUE;
- dispatch_queue_t queue = dispatch_queue_create("pt.diariocoimbra.newsstand.bgqueue", NULL);
- dispatch_async(queue, ^{
- /* put the codes which makes UI unresponsive like reading from network*/
- dispatch_async(dispatch_get_main_queue(), ^{
- /* do the UI related work on main thread */
- _globalProgressBar.progress = 0;
- _globalProgressBar.hidden = false;
- _globalPercentDownload.hidden = false;
- _pleaseWaitWindow.hidden = true;
- //currentDownloadCell.btPrice.titleLabel.text = Wait;
- NSString *msg = [NSString stringWithFormat:@"Download da edição %@ foi iniciado, aguarde",currentDownloadCell.lblDesc.text];
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Download em curso"
- message:msg
- delegate:nil
- cancelButtonTitle:@"fechar"
- otherButtonTitles:nil];
- [alert show];
- NSLog(@"Download started (Updating UI now)...");
- });
- });
- [self downloadIssueAtIndex:indexPath.row];
- }
- }
- }
- @catch (NSException *exception) {
- NSLog(@"ViewController.m :: didSelectItemAtIndexPath crashed");
- }
- }
- #pragma mark - Store
- - (void)paymentStart:(NSString *)bundle{
- if(purchasing_==YES) {
- return;
- }
- purchasing_=YES;
- // product request
- SKProductsRequest *productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:bundle]];
- productsRequest.delegate=self;
- [productsRequest start];
- }
- -(void)requestDidFinish:(SKRequest *)request {
- purchasing_=NO;
- // NSLog(@"Request: %@",request);
- }
- -(void)request:(SKRequest *)request didFailWithError:(NSError *)error {
- purchasing_=NO;
- // NSLog(@"Request %@ failed with error %@",request,error);
- // UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Purchase error" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
- //[alert show];
- }
- -(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
- for(SKProduct *product in response.products) {
- SKPayment *payment = [SKPayment paymentWithProduct:product];
- [[SKPaymentQueue defaultQueue] addPayment:payment];
- }
- }
- -(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
- for(SKPaymentTransaction *transaction in transactions) {
- NSLog(@"Updated transaction %@",transaction);
- switch (transaction.transactionState) {
- case SKPaymentTransactionStateFailed:
- [self errorWithTransaction:transaction];
- interactVar = 1;
- [[NSNotificationCenter defaultCenter] postNotificationName:@"interactWithUI" object:nil userInfo:nil];
- break;
- case SKPaymentTransactionStatePurchasing:
- /* NSLog(@"Purchasing...");*/
- break;
- case SKPaymentTransactionStatePurchased:
- {
- [self finishedTransaction:transaction];
- interactVar = 2;
- [[NSNotificationCenter defaultCenter] postNotificationName:@"interactWithUI" object:nil userInfo:nil];
- NSLog(@"Payment success (Updating UI now)...");
- break;
- }
- case SKPaymentTransactionStateRestored:
- [self finishedTransaction:transaction];
- interactVar = 5;
- [[NSNotificationCenter defaultCenter] postNotificationName:@"interactWithUI" object:nil userInfo:nil];
- break;
- default:
- break;
- }
- }
- }
- - (void)startAnimate{
- _pleaseWaitWindow.hidden = false;
- }
- - (void) interactWithUI
- {
- lastCellSelected = (CustomCell *)[_myCollectionView cellForItemAtIndexPath:lastCellIndex];
- currentDownloadCell = (CustomCell *)[_myCollectionView cellForItemAtIndexPath:currentDownloadIndex];
- NSLog(@"%ld",(long)currentDownloadIndex.row);
- switch (interactVar){
- case 1: // Hides the Big "Please Wait Message"
- _pleaseWaitWindow.hidden = true;
- break;
- case 2: // Informa que o pagamento foi feito com sucesso
- NSLog(@"[SL] Marcando pago o %@", lastCellSelected.lblDesc.text);
- lastCellSelected.btPrice.titleLabel.text = Payed;
- _pleaseWaitWindow.hidden = true;
- NSLog(@"[SL] Novo valor = %@", lastCellSelected.btPrice.titleLabel.text);
- break;
- case 3: // After pressed to download
- currentDownloadCell.btPrice.titleLabel.text = Wait;
- break;
- case 4: // Download concluido com sucesso
- downloadInProgress = FALSE;
- // lastCellSelected.btPrice.titleLabel.text = Downloaded;
- _globalProgressBar.hidden = true;
- _globalPercentDownload.hidden = true;
- currentDownloadCell.btPrice.titleLabel.text = Downloaded;
- break;
- case 5:
- refresh = true;
- [self showIssues];
- if(restuaro){
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Restauro"
- message:@"Operação feita com sucesso volte ao ecrã principal para ser actualizado"
- delegate:nil
- cancelButtonTitle:@"fechar"
- otherButtonTitles:nil];
- [self.navigationController popToRootViewControllerAnimated:YES];
- [alert show];
- }
- restuaro = false;
- break;
- }
- }
- -(void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue {
- }
- -(void)finishedTransaction:(SKPaymentTransaction *)transaction {
- [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
- // save receipt
- [[NSUserDefaults standardUserDefaults] setObject:transaction.transactionIdentifier forKey:@"receiptsIssues.plist"];
- [self checkReceipt:transaction.transactionReceipt];
- [[NSNotificationCenter defaultCenter] postNotificationName:NSInternalInconsistencyException object:nil userInfo:nil];
- //[[NSNotificationCenter defaultCenter] postNotificationName:RefreshNotification object:nil userInfo:nil];
- // [[NSNotificationCenter defaultCenter] postNotificationName:IAPHelperProductPurchasedNotification object:nil userInfo:nil];
- /*
- [buttonsArray removeAllObjects];
- sleep(2);
- [_myCollectionView reloadInputViews];
- [_myCollectionView reloadData];
- */
- // Compra concluída com sucesso
- // interactVar = 2;
- // [[NSNotificationCenter defaultCenter] postNotificationName:@"interactWithUI" object:nil userInfo:nil];
- }
- -(void)errorWithTransaction:(SKPaymentTransaction *)transaction {
- [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Compra"
- message:@"Falhou"
- delegate:nil
- cancelButtonTitle:@"Fechar"
- otherButtonTitles:nil];
- [alert show];
- }
- -(void)checkReceipt:(NSData *)receipt {
- NSString *receiptStorageFile = [DocumentsDirectory stringByAppendingPathComponent:@"receiptsIssues.plist"];
- NSMutableArray *receiptStorage = [[NSMutableArray alloc] initWithContentsOfFile:receiptStorageFile];
- if(!receiptStorage) {
- receiptStorage = [[NSMutableArray alloc] init];
- }
- [receiptStorage addObject:receipt];
- [receiptStorage writeToFile:receiptStorageFile atomically:YES];
- [ReceiptCheck validateReceiptWithData:receipt completionHandler:^(BOOL success,NSString *answer){
- NSError *jsonError = nil;
- NSData *JSONdata = [answer dataUsingEncoding:NSUTF8StringEncoding];
- NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:JSONdata options:0 error:&jsonError];
- NSDictionary *receipt = [dic objectForKey:@"receipt"];
- NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
- if([SixMonths isEqualToString:[receipt objectForKey:@"product_id"]]
- || [OneYear isEqualToString:[receipt objectForKey:@"product_id"]]
- || [ThreeMonths isEqualToString:[receipt objectForKey:@"product_id"]]
- || [OneMonth isEqualToString:[receipt objectForKey:@"product_id"]]
- || [Week isEqualToString:[receipt objectForKey:@"product_id"]]
- ){
- [prefs setObject: [receipt objectForKey:@"expires_date_formatted"] forKey:@"expires_date_formatted"];
- [prefs setObject: [receipt objectForKey:@"purchase_date"] forKey:@"purchase_date"];
- [prefs setObject: [receipt objectForKey:@"product_id"] forKey:@"product_id"];
- }else{
- NSMutableArray *bundles;
- if([prefs objectForKey:@"bundle"]==nil)
- bundles = [[NSMutableArray alloc]init];
- else
- bundles = [[prefs objectForKey:@"bundle"] mutableCopy];
- @try {
- [bundles addObject:[receipt objectForKey:@"product_id"]];
- [prefs setObject:bundles forKey:@"bundle"];
- }
- @catch (NSException *exception) {
- NSLog(@"%@",exception);
- NSLog(@"deu merda ta claro");
- }
- }
- if(success==YES)
- {
- [self fastIssueBuyitSave:answer];
- NSLog(@"Receipt has been validated: %@",answer);
- } else {
- NSLog(@"Receipt not validated! Error: %@",answer);
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Erro na compra" message:@"Não foi possivel validar o pagamento" delegate:nil cancelButtonTitle:@"Fechar" otherButtonTitles:nil];
- [alert show];
- };
- }];
- }
- -(void)fastIssueBuyitSave:(NSString *)message{
- NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
- issuesBuyit = [[defaults objectForKey:@"issuesBuyit"]mutableCopy];
- if(issuesBuyit == nil)
- issuesBuyit = [[NSMutableArray alloc] init];
- NSError *jsonError = nil;
- NSData *JSONdata = [message dataUsingEncoding:NSUTF8StringEncoding];
- NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:JSONdata options:0 error:&jsonError];
- NSDictionary *receipt = [dic objectForKey:@"receipt"];
- [issuesBuyit addObject:[NSString stringWithFormat:@"%@",[receipt objectForKey:@"product_id"]]];
- [defaults setObject:issuesBuyit forKey:@"issuesBuyit"];
- [defaults synchronize];
- }
- #pragma mark - Check all saved receipts
- -(int)checkReceipts:(NSString *)date{
- // open receipts
- ret=0;
- NSArray *receipts = [[NSArray alloc] initWithContentsOfFile:[DocumentsDirectory stringByAppendingPathComponent:@"receiptsIssues.plist"]];
- if(!receipts || [receipts count]==0) {
- // NSLog(@"ViewController.m : checkReceipts / No receiptsIssues.plist file found");
- return 0;
- }
- NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
- if(![prefs objectForKey:@"product_id"])
- {
- // NSLog(@"ViewController.m : checkReceipts / No prefs:objectForKey:product_id found");
- return 0;
- }
- NSLog(@"ViewController.m : checkReceipts / purchase_date = %@",[prefs objectForKey:@"purchase_date"]);
- NSLog(@"ViewController.m : checkReceipts / expires_dat_formatted = %@",[prefs objectForKey:@"expires_date_formatted"]);
- if([self dateBetweenDates:[prefs objectForKey:@"purchase_date"] :[prefs objectForKey:@"expires_date_formatted"]:date])
- {
- NSLog(@"ViewController.m : checkReceipts / InApp Purchase OK");
- return 1;
- }
- NSLog(@"ViewController.m : checkReceipts / No InApp Purchase found");
- return 0;
- }
- -(int)checkBundleList:(NSString *)bundle{
- NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
- issuesBuyit = [[defaults objectForKey:@"issuesBuyit"] mutableCopy];
- for(int i = 0; i < [issuesBuyit count];i++){
- if([bundle isEqualToString:[issuesBuyit objectAtIndex:i]])
- return 1;
- }
- return 0;
- }
- -(void)reload{
- /* [buttonsArray removeAllObjects];
- sleep(5);
- [_myCollectionView reloadInputViews];
- [_myCollectionView reloadData];*/
- // [self performSelectorInBackground:@selector(reload2) withObject:nil];
- }
- -(void)reload2{
- /* [buttonsArray removeAllObjects];
- sleep(5);
- [_myCollectionView reloadInputViews];
- [_myCollectionView reloadData];*/
- }
- -(BOOL)dateBetweenDates:(NSString *)dateSrt{
- NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
- NSDateFormatter *df=[[NSDateFormatter alloc]init];
- NSString *aux = [NSString stringWithFormat:@"%@",dateSrt];
- NSArray *fields = [aux componentsSeparatedByString:@" "];
- df.dateFormat = @"yyyy-MM-dd";
- NSDate *today = [df dateFromString:[fields objectAtIndex:0]];
- NSDate *dateInicio = [df dateFromString:[prefs objectForKey:@"data_inicio"]];
- NSDate *dateFim = [df dateFromString:[prefs objectForKey:@"data_fim"]];
- NSComparisonResult resultInicio,resultFim;
- resultInicio = [today compare:dateInicio];
- resultFim = [today compare:dateFim];
- if((resultInicio == NSOrderedDescending && resultFim == NSOrderedAscending) || resultInicio == NSOrderedSame || resultFim == NSOrderedSame)
- return true;
- else
- return false;
- }
- -(BOOL)dateBetweenDates:(NSString *)dateBegin:(NSString *)dateEnd:(NSString *)issue{
- NSDateFormatter *df=[[NSDateFormatter alloc]init];
- df.dateFormat = @"yyyy-MM-dd";
- NSString *aux = [NSString stringWithFormat:@"%@",dateBegin];
- NSArray *fields = [aux componentsSeparatedByString:@" "];
- NSString *aux2 = [NSString stringWithFormat:@"%@",dateEnd];
- NSArray *fields2 = [aux2 componentsSeparatedByString:@" "];
- NSString *aux3= [NSString stringWithFormat:@"%@",issue];
- NSArray *fields3 = [aux3 componentsSeparatedByString:@" "];
- NSDate *min = [df dateFromString:[fields objectAtIndex:0]];
- NSDate *max = [df dateFromString:[fields2 objectAtIndex:0]];
- //NSDate *min = [df dateFromString:@"2013-01-03"];
- //NSDate *max = [df dateFromString:@"2013-09-09"];
- NSDate *today = [df dateFromString:[fields3 objectAtIndex:0]];
- NSComparisonResult resultInicio,resultFim;
- resultInicio = [today compare:min]; //Same
- resultFim = [today compare:max];//Descending
- if((resultInicio == NSOrderedDescending && resultFim == NSOrderedAscending) || resultFim == NSOrderedSame || resultInicio == NSOrderedSame)
- return true;
- else
- return false;
- }
- -(void)refreshLogin{
- interactVar = 5;
- [[NSNotificationCenter defaultCenter] postNotificationName:@"interactWithUI" object:nil userInfo:nil];
- }
- -(void)Reachability{
- Reachability *internetReachableFoo;
- internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"];
- // Internet is reachable
- internetReachableFoo.reachableBlock = ^(Reachability*reach)
- {
- // Update the UI on the main thread
- dispatch_async(dispatch_get_main_queue(), ^{
- haveNet= true;
- });
- };
- // Internet is not reachable
- internetReachableFoo.unreachableBlock = ^(Reachability*reach)
- {
- // Update the UI on the main thread
- dispatch_async(dispatch_get_main_queue(), ^{
- haveNet= false;
- });
- };
- [internetReachableFoo startNotifier];
- }
- -(void)SetBanner{
- if(haveNet){
- NSString *device = [[UIDevice currentDevice] model];
- NSURL *url;
- NSString *myString;
- @try {
- int count =0;
- do {
- sleep(1);
- UIInterfaceOrientation orientation= [[UIApplication sharedApplication] statusBarOrientation];
- if([device isEqualToString:@"iPad"]&& UIInterfaceOrientationIsLandscape(orientation))
- url = [[NSURL alloc] initWithString:[JsonPost shareGlobalData].ipadL];
- else if([device isEqualToString:@"iPad"]&& UIInterfaceOrientationIsPortrait(orientation))
- url = [[NSURL alloc] initWithString:[JsonPost shareGlobalData].ipadP];
- else if([device isEqualToString:@"iPhone"]&& UIInterfaceOrientationIsLandscape(orientation))
- url = [[NSURL alloc] initWithString:[JsonPost shareGlobalData].iphoneL];
- else if([device isEqualToString:@"iPhone"]&& UIInterfaceOrientationIsPortrait(orientation))
- url = [[NSURL alloc] initWithString:[JsonPost shareGlobalData].iphoneP];
- else
- url = [[NSURL alloc] initWithString:[JsonPost shareGlobalData].ipadL];
- count++;
- myString = [url absoluteString];
- } while ([myString isEqualToString:@"NIL"]|| count ==3); //tenta 10x no maximo até ter o url
- NSData * imageData = [NSData dataWithContentsOfURL:url];
- UIImage * image = [UIImage imageWithData:imageData];
- _banner.image = image;
- }
- @catch (NSException *exception) {
- NSLog(@"Crach why -> %@",exception);
- NSLog(@"[SLf] ViewController :: SetBanner crashed...");
- }
- }
- // Enable the menu
- //[_loadingActivity stopAnimating];
- // _loadingActivity.hidden = TRUE;
- _pleaseWaitWindow.hidden = true;
- _barButton.enabled = YES;
- }
- -(void)loadBanner{
- }
- - (void)viewDidUnload {
- [self setBanner:nil];
- [super viewDidUnload];
- }
- - (IBAction)bannerPressed:(id)sender {
- @try {
- NSString *url = [JsonPost shareGlobalData].bannerURL;
- url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
- [[UIApplication sharedApplication]openURL:[NSURL URLWithString:url]];
- }
- @catch (NSException *exception) {
- NSLog(@"Fudeu-se");
- }
- }
- -(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
- if(toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight){
- _myCollectionView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
- [[self navigationController] setNavigationBarHidden:YES];
- }
- else{
- [[self navigationController] setNavigationBarHidden:NO];
- }
- [self SetBanner];
- }
- - (void)Restore {
- [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
- NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
- NSArray *receipts = [[NSArray alloc] initWithContentsOfFile:[DocumentsDirectory stringByAppendingPathComponent:@"receiptsIssues.plist"]];
- if(!receipts || [receipts count]==0) {
- return;
- }
- for(NSData *aReceipt in receipts) {
- [ReceiptCheck validateReceiptWithData:aReceipt completionHandler:^(BOOL success, NSString *message) {
- NSError *jsonError = nil;
- NSData *JSONdata = [message dataUsingEncoding:NSUTF8StringEncoding];
- NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:JSONdata options:0 error:&jsonError];
- NSDictionary *receipt = [dic objectForKey:@"receipt"];
- if([SixMonths isEqualToString:[receipt objectForKey:@"product_id"]])
- [prefs setObject:SixMonths forKey:@"Subscription"];
- else if([OneYear isEqualToString:[receipt objectForKey:@"product_id"]])
- [prefs setObject:OneYear forKey:@"Subscription"];
- else if([OneMonth isEqualToString:[receipt objectForKey:@"product_id"]])
- [prefs setObject:OneMonth forKey:@"Subscription"];
- else if([Week isEqualToString:[receipt objectForKey:@"product_id"]])
- [prefs setObject:Week forKey:@"Subscription"];
- else if([ThreeMonths isEqualToString:[receipt objectForKey:@"product_id"]])
- [prefs setObject:ThreeMonths forKey:@"Subscription"];
- }
- ];
- }
- }
- @end
Add Comment
Please, Sign In to add comment