Guest User

Untitled

a guest
Nov 8th, 2017
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 40.49 KB | None | 0 0
  1. //
  2. // ViewController.m
  3. // newsstand
  4. //
  5. // Created by joao vitor on 02/05/13.
  6. // Copyright (c) 2013 joao vitor. All rights reserved.
  7. //
  8.  
  9. #import "ViewController.h"
  10. #import "CustomCell.h"
  11. #import "Publisher.h"
  12. #import "ReceiptCheck.h"
  13. #import "InAppViewController.h"
  14. #include <unistd.h>
  15. #include "JsonPost.h"
  16. #include "Reachability.h"
  17. @interface ViewController ()
  18. @property (nonatomic, strong) NSOperationQueue *thumbnailQueue;
  19. -(void)showIssues;
  20. -(void)loadIssues;
  21. -(void)readIssue:(NKIssue *)nkIssue;
  22. -(void)downloadIssueAtIndex:(NSInteger)index;
  23.  
  24. -(void)errorWithTransaction:(SKPaymentTransaction *)transaction;
  25. -(void)finishedTransaction:(SKPaymentTransaction *)transaction;
  26. -(void)checkReceipt:(NSData *)receipt;
  27. - (NSString *)decodeBase64:(NSString *)input;
  28. - (void) interactWithUIAction;
  29. @end
  30.  
  31. @implementation ViewController
  32. @synthesize purchasing=purchasing_;
  33. Publisher *publisher;
  34. NSArray *issues;
  35. CustomCell *lastCellSelected;
  36. CustomCell *currentDownloadCell;
  37. bool downloadInProgress = FALSE;
  38. int interactVar = 0;
  39. NSTimer *timer;
  40.  
  41. NSMutableSet *indexPathsNeedingImages;
  42. NSIndexPath *lastCellIndex;
  43. NSIndexPath *currentDownloadIndex;
  44. BOOL refresh;
  45. BOOL haveNet;
  46. BOOL restuaro;
  47. - (void)viewDidLoad
  48. {
  49. restuaro = true;
  50. refresh = true;
  51. _pleaseWaitWindow.hidden = false;
  52.  
  53. [super viewDidLoad];
  54. buttonsArray = [[NSMutableArray alloc] init];
  55.  
  56. if([publisher isReady]) {
  57. [self showIssues];
  58. } else {
  59. [self loadIssues];
  60. }
  61.  
  62. [self Reachability];
  63.  
  64. [[self myCollectionView] setDataSource:self];
  65. [[self myCollectionView] setDelegate:self];
  66.  
  67. // Notificacoes de sistema...
  68. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reload) name:IAPHelperProductPurchasedNotification object:nil];
  69. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshLogin) name:DismissPopoverNotification object:nil];
  70. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(interactWithUI) name:@"interactWithUI" object:nil];
  71. [[NSNotificationCenter defaultCenter] addObserver:self
  72. selector:@selector(forceUpdate)
  73. name:@"appDidBecomeActive"
  74. object:nil];
  75. [[NSUserDefaults standardUserDefaults] synchronize];
  76.  
  77. [self performSelector:@selector(startBanner) withObject:nil afterDelay:2.0];
  78. }
  79.  
  80. -(void)viewDidAppear:(BOOL)animated{
  81. refresh = true;
  82. }
  83.  
  84. -(void)forceUpdate{
  85. [self loadIssues];
  86. }
  87.  
  88. - (void)viewWillAppear:(BOOL)animated{
  89.  
  90. issuesBuyit = [[NSMutableArray alloc] init];
  91. NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
  92. issuesBuyit = [[defaults objectForKey:@"issuesBuyit"] mutableCopy];
  93.  
  94. }
  95.  
  96. -(void)startBanner{
  97. @try {
  98. [[JsonPost shareGlobalData] postMessageGetBanner];
  99. [self performSelectorInBackground:@selector(SetBanner) withObject:nil];
  100. }
  101. @catch (NSException *exception) {
  102. NSLog(@"Banner no fundo crashou.");
  103. }
  104. }
  105.  
  106.  
  107. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
  108. {
  109. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  110. if (self) {
  111. // Custom initialization
  112. publisher = [[Publisher alloc] init];
  113. }
  114. return self;
  115. }
  116.  
  117. - (void)didReceiveMemoryWarning
  118. {
  119. [super didReceiveMemoryWarning];
  120. // Dispose of any resources that can be recreated.
  121. }
  122.  
  123.  
  124. #pragma mark - Issue actions
  125.  
  126. -(void)readIssue:(NKIssue *)nkIssue {
  127.  
  128.  
  129. //--
  130.  
  131.  
  132. [[NKLibrary sharedLibrary] setCurrentlyReadingIssue:nkIssue];
  133.  
  134.  
  135.  
  136.  
  137.  
  138. NSString *phrase = nil; // Document password (for unlocking most encrypted PDF files)
  139.  
  140.  
  141. ReaderDocument *document = [ReaderDocument withDocumentFilePath:[publisher downloadPathForIssue:nkIssue] password:phrase];
  142.  
  143. if (document != nil) // Must have a valid ReaderDocument object in order to proceed with things
  144. {
  145. ReaderViewController *readerViewController = [[ReaderViewController alloc] initWithReaderDocument:document];
  146.  
  147. readerViewController.delegate = self; // Set the ReaderViewController delegate to self
  148.  
  149. #if (DEMO_VIEW_CONTROLLER_PUSH == TRUE)
  150.  
  151. [self.navigationController pushViewController:readerViewController animated:YES];
  152.  
  153. #else // present in a modal view controller
  154.  
  155. readerViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
  156. readerViewController.modalPresentationStyle = UIModalPresentationFullScreen;
  157.  
  158. [self presentModalViewController:readerViewController animated:YES];
  159.  
  160. #endif // DEMO_VIEW_CONTROLLER_PUSH
  161. }
  162.  
  163.  
  164. }
  165. - (void)dismissReaderViewController:(ReaderViewController *)viewController {
  166. // [self dismissModalViewControllerAnimated:YES];
  167. [self dismissViewControllerAnimated:YES completion:nil];
  168. }
  169. -(void)downloadIssueAtIndex:(NSInteger)index {
  170. NKLibrary *nkLib = [NKLibrary sharedLibrary];
  171. NKIssue *nkIssue = [nkLib issueWithName:[publisher nameOfIssueAtIndex:index]];
  172. NSURL *downloadURL = [publisher contentURLForIssueWithName:nkIssue.name];
  173. if(!downloadURL) return;
  174. NSURLRequest *req = [NSURLRequest requestWithURL:downloadURL];
  175. NKAssetDownload *assetDownload = [nkIssue addAssetWithRequest:req];
  176.  
  177. [assetDownload downloadWithDelegate:self];
  178. [assetDownload setUserInfo:[NSDictionary dictionaryWithObjectsAndKeys:
  179. [NSNumber numberWithInt:index],@"Index",
  180. nil]];
  181.  
  182.  
  183. downloadInProgress = TRUE;
  184. dispatch_queue_t queue = dispatch_queue_create("pt.diariocoimbra.newsstand.bgqueue", NULL);
  185. dispatch_async(queue, ^{
  186. /* put the codes which makes UI unresponsive like reading from network*/
  187.  
  188. dispatch_async(dispatch_get_main_queue(), ^{
  189. /* do the UI related work on main thread */
  190. _globalProgressBar.progress = 0;
  191. _globalProgressBar.hidden = FALSE;
  192. _globalPercentDownload.hidden = FALSE;
  193. //[_myCollectionView reloadData]; -------
  194. NSLog(@"Download starting (Updating UI now)...");
  195. });
  196. });
  197.  
  198.  
  199. }
  200.  
  201.  
  202. #pragma mark - NSURLConnectionDownloadDelegate
  203.  
  204. -(void)updateProgressOfConnection:(NSURLConnection *)connection withTotalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long)expectedTotalBytes
  205. {
  206. float current_value = 1.f*totalBytesWritten/expectedTotalBytes;
  207. _globalProgressBar.progress = current_value;
  208. NSString *strFromInt = [NSString stringWithFormat:@"%3.0f%@", (current_value*100), @"\%"];
  209. [_globalPercentDownload setText:strFromInt];
  210. }
  211.  
  212. -(void)connection:(NSURLConnection *)connection didWriteData:(long long)bytesWritten totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long)expectedTotalBytes {
  213. [self updateProgressOfConnection:connection withTotalBytesWritten:totalBytesWritten expectedTotalBytes:expectedTotalBytes];
  214. }
  215.  
  216. -(void)connectionDidResumeDownloading:(NSURLConnection *)connection totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long)expectedTotalBytes {
  217. [self updateProgressOfConnection:connection withTotalBytesWritten:totalBytesWritten expectedTotalBytes:expectedTotalBytes];
  218. }
  219.  
  220.  
  221. // O download terminou com sucesso ...
  222. -(void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL
  223. {
  224.  
  225.  
  226. currentDownloadCell = (CustomCell *)[_myCollectionView cellForItemAtIndexPath:currentDownloadIndex];
  227.  
  228. //nova linha alterada
  229.  
  230.  
  231. // copy file to destination URL
  232. NKAssetDownload *dnl = connection.newsstandAssetDownload;
  233. NKIssue *nkIssue = dnl.issue;
  234. NSString *contentPath = [publisher downloadPathForIssue:nkIssue];
  235. NSError *moveError=nil;
  236. if([[NSFileManager defaultManager] moveItemAtPath:[destinationURL path] toPath:contentPath error:&moveError]==NO) {
  237. NSLog(@"Error copying file from %@ to %@",destinationURL,contentPath);
  238. }
  239.  
  240. // update the Newsstand icon
  241. UIImage *img = [publisher coverImageForIssue:nkIssue];
  242. if(img) {
  243. [[UIApplication sharedApplication] setNewsstandIconImage:img];
  244. [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
  245. }
  246.  
  247. // [self showIssues];
  248. // interactVar = 4;
  249. // [[NSNotificationCenter defaultCenter] postNotificationName:@"interactWithUI" object:nil userInfo:nil];
  250. downloadInProgress = FALSE;
  251. dispatch_queue_t queue = dispatch_queue_create("pt.diariocoimbra.newsstand.bgqueue", NULL);
  252. dispatch_async(queue, ^{
  253. /* put the codes which makes UI unresponsive like reading from network*/
  254. dispatch_async(dispatch_get_main_queue(), ^{
  255. /* do the UI related work on main thread */
  256. _globalProgressBar.hidden = true;
  257. _globalPercentDownload.hidden = true;
  258. currentDownloadCell.btPrice.titleLabel.text = Downloaded;
  259. _pleaseWaitWindow.hidden = true;
  260. // [_myCollectionView reloadData];
  261. NSLog(@"Download sucsess (Updating UI now)...");
  262. });
  263. });
  264. //[_myCollectionView reloadInputViews];
  265.  
  266. }
  267.  
  268. #pragma mark - Publisher interaction
  269.  
  270. -(void)loadIssues {
  271. NSLog(@"Tou aqui");
  272. NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
  273.  
  274. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(publisherReady:) name:PublisherDidUpdateNotification object:publisher];
  275. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(publisherFailed:) name:PublisherFailedUpdateNotification object:publisher];
  276.  
  277.  
  278. [publisher getIssuesList];
  279. }
  280.  
  281. -(void)publisherReady:(NSNotification *)not {
  282. [[NSNotificationCenter defaultCenter] removeObserver:self name:PublisherDidUpdateNotification object:publisher];
  283. [[NSNotificationCenter defaultCenter] removeObserver:self name:PublisherFailedUpdateNotification object:publisher];
  284. [self showIssues];
  285. }
  286.  
  287. -(void)showIssues {
  288. NSLog(@"Show issues...");
  289. if (refresh) {
  290. [buttonsArray removeAllObjects];
  291. [_myCollectionView reloadData];
  292. [_myCollectionView reloadInputViews];
  293. }
  294. refresh = false;
  295. }
  296.  
  297. -(void)publisherFailed:(NSNotification *)not {
  298.  
  299. [[NSNotificationCenter defaultCenter] removeObserver:self name:PublisherDidUpdateNotification object:publisher];
  300. [[NSNotificationCenter defaultCenter] removeObserver:self name:PublisherFailedUpdateNotification object:publisher];
  301. // NSLog(@"%@",not);
  302. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Erro"
  303. message:@"Verifique a sua ligação"
  304. delegate:nil
  305. cancelButtonTitle:@"Close"
  306. otherButtonTitles:nil];
  307. [alert show];
  308.  
  309. }
  310.  
  311. #pragma mark - Collection
  312.  
  313. // Uma coleccao de edicoes (o grupo das 15)
  314. - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
  315. return 1;
  316. }
  317.  
  318. // Numero de edicoes que vao ser carregadas
  319. - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
  320. NSLog(@"[SL] numberOfItemsInSection = %d", [publisher numberOfIssues]);
  321. return [publisher numberOfIssues];
  322. }
  323.  
  324. - (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
  325. [indexPathsNeedingImages removeObject:indexPath];
  326. // NSLog(@"[SL] Removing hidden Cell # %d", indexPath.row);
  327. }
  328.  
  329.  
  330. -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  331. {
  332. // PQP
  333. CustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
  334.  
  335. NSInteger index = indexPath.item;
  336.  
  337. // NSLog(@"[SL] Loading Cell | indexPath.row = %d / item = %ld / Label = %@ / Total = %d", indexPath.row, indexPath.item, cell.lblDesc.text, itemCount);
  338. /* for (int i = 0; i < 15 ; i++)
  339. NSLog(@"[SL] data at # %d : Name = %@", i, [publisher nameOfIssueAtIndex:i]);*/
  340.  
  341. //if ([cell.lblDesc.text isEqualToString:@"Label"])
  342. {
  343.  
  344. NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
  345.  
  346. [[cell lblDesc] setText:[publisher titleOfIssueAtIndex:index]];
  347. // NSString *strFromInt = [NSString stringWithFormat:@"%@%@%@", [publisher titleOfIssueAtIndex:index], @" ", [NSString stringWithFormat:@"%d", index]];
  348. // [[cell lblDesc] setText:strFromInt];
  349.  
  350. NKLibrary *nkLib = [NKLibrary sharedLibrary];
  351. NKIssue *nkIssue = [nkLib issueWithName:[publisher nameOfIssueAtIndex:index]];
  352.  
  353.  
  354. [publisher setCoverOfIssueAtIndex:index completionBlock:^(UIImage *img) {
  355. [self performSelectorOnMainThread:@selector(threadForImage:) withObject:[NSArray arrayWithObjects:cell,img, nil] waitUntilDone:NO];
  356. }];
  357.  
  358. //checkReceipts -> verifica Individual
  359. //dateBetweenDates -> data forçada
  360.  
  361.  
  362. // NSLog(@"[SL] ViewController.m : cellForItemAtIndexPath : data_inicio = %@",[prefs objectForKey:@"data_inicio"]);
  363. // NSLog(@"[SL] ViewController.m : cellForItemAtIndexPath : dateofIssueAtIndex = %@", [publisher dateOfIssueAtIndex:index]);
  364. // NSLog(@"[SL] ViewController.m : cellForItemAtIndexPath : bundleofIssue = %@", [publisher bundleOfIssueAtIndex:index]);
  365. // NSLog(@"[SL] ViewController.m : cellForItemAtIndexPath : checkReceipts = %d", [self checkReceipts:[publisher dateOfIssueAtIndex:index]]);
  366.  
  367. /*
  368. CustomCell *aux= (CustomCell *)[_myCollectionView cellForItemAtIndexPath:currentDownloadIndex];
  369. NSLog(@"Download %@",currentDownloadCell.lblDesc.text);
  370. NSLog(@" Carregado %@",[publisher titleOfIssueAtIndex:index]);
  371. NSLog(@" Index %ld",(long)currentDownloadIndex.row);
  372. if ([[[aux lblDesc] text] isEqualToString:[publisher titleOfIssueAtIndex:index]])
  373. {
  374. [[cell btPrice] setTitle: @"Aguarde" forState:UIControlStateNormal];
  375. }
  376. else
  377. {*/
  378. if([self checkReceipts:[publisher dateOfIssueAtIndex:index]] == 1 || // Se subscricao Apple Activa
  379. ([self dateBetweenDates:[publisher dateOfIssueAtIndex:index]] == true && [prefs objectForKey:@"data_inicio"]!=nil) // ... ou se Subscricao Nao Apple Activa
  380. ){
  381.  
  382. if(nkIssue.status == NKIssueContentStatusAvailable)
  383. [cell.btPrice setTitle:Downloaded forState:UIControlStateNormal];
  384. else
  385. [cell.btPrice setTitle:Subscribed forState:UIControlStateNormal];
  386. }
  387. else
  388. { // Caso nao exista nenhuma das subscricoes activas (apple ou nao apple)
  389. if([self checkBundleList:[publisher bundleOfIssueAtIndex:index]] == 0) // se nao existe uma compra apple individual comprada
  390. [cell.btPrice setTitle:[publisher priceOfIssueAtIndex:index] forState:UIControlStateNormal];
  391. else{
  392. if(nkIssue.status==NKIssueContentStatusAvailable)
  393. [cell.btPrice setTitle:Downloaded forState:UIControlStateNormal];
  394. else
  395. [cell.btPrice setTitle:Payed forState:UIControlStateNormal];
  396. }
  397. }
  398. // }
  399.  
  400. [buttonsArray addObject:cell.btPrice.titleLabel.text];
  401.  
  402.  
  403.  
  404. }
  405.  
  406. return cell;
  407. }
  408.  
  409. -(void)threadForImage:(NSArray*)array{
  410. NSLog(@"A buscar imagem...");
  411. CustomCell *cell = [array objectAtIndex:0];
  412. UIImage *img = [array objectAtIndex:1];
  413. // lastCell.image.image = img;
  414.  
  415. cell.image.image = img;
  416. }
  417.  
  418. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
  419.  
  420. @try {
  421.  
  422. lastCellSelected = (CustomCell *)[collectionView cellForItemAtIndexPath:indexPath];
  423. lastCellIndex = indexPath;
  424. NSString *aux = lastCellSelected.btPrice.titleLabel.text;
  425. NSLog(@"[SL] Pressionei %ld", (long)indexPath.row);
  426.  
  427. if(![aux isEqualToString:Subscribed] &&
  428. ![aux isEqualToString:Payed] &&
  429. ![aux isEqualToString:Wait] &&
  430. ![aux isEqualToString:Downloaded])
  431. {
  432. if(!haveNet){
  433.  
  434. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Modo Offline" message:@"Necessita de internet para fazer uma compra" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
  435. [alert show];
  436. return;
  437. }
  438.  
  439.  
  440. [self performSelectorOnMainThread:@selector(startAnimate) withObject:nil waitUntilDone:YES];
  441. dispatch_queue_t queue = dispatch_queue_create("pt.diariocoimbra.newsstand.bgqueue", NULL);
  442. dispatch_async(queue, ^{
  443. /* put the codes which makes UI unresponsive like reading from network*/
  444. dispatch_async(dispatch_get_main_queue(), ^{
  445. /* do the UI related work on main thread */
  446. _pleaseWaitWindow.hidden = false;
  447. // [_myCollectionView reloadData]; ----------
  448. NSLog(@"Buying started (Updating UI now)...");
  449. });
  450. });
  451. [self paymentStart:[publisher bundleOfIssueAtIndex:indexPath.row]];
  452. }
  453. else
  454. {
  455. NKLibrary *nkLib = [NKLibrary sharedLibrary];
  456. NKIssue *nkIssue = [nkLib issueWithName:[publisher nameOfIssueAtIndex:indexPath.row]];
  457.  
  458.  
  459. if(nkIssue.status==NKIssueContentStatusAvailable) {
  460. [self readIssue:nkIssue];
  461. } else if(nkIssue.status==NKIssueContentStatusNone) {
  462.  
  463. if(!haveNet){
  464.  
  465. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Modo Offline" message:@"Necessita de internet para descarregar esta edição" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
  466. [alert show];
  467. return;
  468. }
  469.  
  470. // Download em progresso: Não permito outras interaccoes com a grelha de edicoes
  471. if (downloadInProgress)
  472. {
  473. _globalProgressBar.hidden = FALSE;
  474. _globalPercentDownload.hidden = FALSE;
  475. return;
  476. }
  477.  
  478. currentDownloadCell = (CustomCell *)[collectionView cellForItemAtIndexPath:indexPath];
  479. currentDownloadIndex = indexPath;
  480. // interactVar = 3;
  481. // [[NSNotificationCenter defaultCenter] postNotificationName:@"interactWithUI" object:nil userInfo:nil];
  482. // [[NSNotificationCenter defaultCenter] postNotificationName:@"interactWithUI" object:nil userInfo:nil];
  483. downloadInProgress = TRUE;
  484. dispatch_queue_t queue = dispatch_queue_create("pt.diariocoimbra.newsstand.bgqueue", NULL);
  485. dispatch_async(queue, ^{
  486. /* put the codes which makes UI unresponsive like reading from network*/
  487. dispatch_async(dispatch_get_main_queue(), ^{
  488. /* do the UI related work on main thread */
  489. _globalProgressBar.progress = 0;
  490. _globalProgressBar.hidden = false;
  491. _globalPercentDownload.hidden = false;
  492. _pleaseWaitWindow.hidden = true;
  493. //currentDownloadCell.btPrice.titleLabel.text = Wait;
  494.  
  495. NSString *msg = [NSString stringWithFormat:@"Download da edição %@ foi iniciado, aguarde",currentDownloadCell.lblDesc.text];
  496.  
  497. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Download em curso"
  498. message:msg
  499. delegate:nil
  500. cancelButtonTitle:@"fechar"
  501. otherButtonTitles:nil];
  502. [alert show];
  503. NSLog(@"Download started (Updating UI now)...");
  504. });
  505. });
  506.  
  507. [self downloadIssueAtIndex:indexPath.row];
  508. }
  509.  
  510. }
  511. }
  512. @catch (NSException *exception) {
  513. NSLog(@"ViewController.m :: didSelectItemAtIndexPath crashed");
  514. }
  515. }
  516.  
  517.  
  518. #pragma mark - Store
  519.  
  520. - (void)paymentStart:(NSString *)bundle{
  521. if(purchasing_==YES) {
  522. return;
  523. }
  524. purchasing_=YES;
  525. // product request
  526. SKProductsRequest *productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:bundle]];
  527.  
  528. productsRequest.delegate=self;
  529. [productsRequest start];
  530.  
  531. }
  532.  
  533. -(void)requestDidFinish:(SKRequest *)request {
  534. purchasing_=NO;
  535. // NSLog(@"Request: %@",request);
  536.  
  537. }
  538.  
  539. -(void)request:(SKRequest *)request didFailWithError:(NSError *)error {
  540. purchasing_=NO;
  541. // NSLog(@"Request %@ failed with error %@",request,error);
  542. // UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Purchase error" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
  543. //[alert show];
  544.  
  545. }
  546.  
  547. -(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
  548. for(SKProduct *product in response.products) {
  549. SKPayment *payment = [SKPayment paymentWithProduct:product];
  550. [[SKPaymentQueue defaultQueue] addPayment:payment];
  551. }
  552.  
  553. }
  554.  
  555.  
  556.  
  557. -(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
  558.  
  559.  
  560. for(SKPaymentTransaction *transaction in transactions) {
  561. NSLog(@"Updated transaction %@",transaction);
  562. switch (transaction.transactionState) {
  563. case SKPaymentTransactionStateFailed:
  564. [self errorWithTransaction:transaction];
  565. interactVar = 1;
  566. [[NSNotificationCenter defaultCenter] postNotificationName:@"interactWithUI" object:nil userInfo:nil];
  567. break;
  568. case SKPaymentTransactionStatePurchasing:
  569. /* NSLog(@"Purchasing...");*/
  570. break;
  571. case SKPaymentTransactionStatePurchased:
  572. {
  573. [self finishedTransaction:transaction];
  574. interactVar = 2;
  575. [[NSNotificationCenter defaultCenter] postNotificationName:@"interactWithUI" object:nil userInfo:nil];
  576. NSLog(@"Payment success (Updating UI now)...");
  577.  
  578. break;
  579. }
  580. case SKPaymentTransactionStateRestored:
  581. [self finishedTransaction:transaction];
  582. interactVar = 5;
  583. [[NSNotificationCenter defaultCenter] postNotificationName:@"interactWithUI" object:nil userInfo:nil];
  584. break;
  585. default:
  586. break;
  587. }
  588. }
  589.  
  590.  
  591. }
  592.  
  593. - (void)startAnimate{
  594. _pleaseWaitWindow.hidden = false;
  595. }
  596.  
  597. - (void) interactWithUI
  598. {
  599. lastCellSelected = (CustomCell *)[_myCollectionView cellForItemAtIndexPath:lastCellIndex];
  600. currentDownloadCell = (CustomCell *)[_myCollectionView cellForItemAtIndexPath:currentDownloadIndex];
  601.  
  602. NSLog(@"%ld",(long)currentDownloadIndex.row);
  603.  
  604. switch (interactVar){
  605. case 1: // Hides the Big "Please Wait Message"
  606. _pleaseWaitWindow.hidden = true;
  607. break;
  608. case 2: // Informa que o pagamento foi feito com sucesso
  609. NSLog(@"[SL] Marcando pago o %@", lastCellSelected.lblDesc.text);
  610. lastCellSelected.btPrice.titleLabel.text = Payed;
  611. _pleaseWaitWindow.hidden = true;
  612. NSLog(@"[SL] Novo valor = %@", lastCellSelected.btPrice.titleLabel.text);
  613. break;
  614. case 3: // After pressed to download
  615. currentDownloadCell.btPrice.titleLabel.text = Wait;
  616. break;
  617. case 4: // Download concluido com sucesso
  618. downloadInProgress = FALSE;
  619. // lastCellSelected.btPrice.titleLabel.text = Downloaded;
  620. _globalProgressBar.hidden = true;
  621. _globalPercentDownload.hidden = true;
  622. currentDownloadCell.btPrice.titleLabel.text = Downloaded;
  623. break;
  624. case 5:
  625. refresh = true;
  626.  
  627. [self showIssues];
  628.  
  629. if(restuaro){
  630. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Restauro"
  631. message:@"Operação feita com sucesso volte ao ecrã principal para ser actualizado"
  632. delegate:nil
  633. cancelButtonTitle:@"fechar"
  634. otherButtonTitles:nil];
  635.  
  636. [self.navigationController popToRootViewControllerAnimated:YES];
  637. [alert show];
  638. }
  639. restuaro = false;
  640. break;
  641. }
  642. }
  643.  
  644.  
  645.  
  646.  
  647.  
  648. -(void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue {
  649.  
  650. }
  651.  
  652. -(void)finishedTransaction:(SKPaymentTransaction *)transaction {
  653.  
  654.  
  655. [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
  656. // save receipt
  657. [[NSUserDefaults standardUserDefaults] setObject:transaction.transactionIdentifier forKey:@"receiptsIssues.plist"];
  658.  
  659. [self checkReceipt:transaction.transactionReceipt];
  660. [[NSNotificationCenter defaultCenter] postNotificationName:NSInternalInconsistencyException object:nil userInfo:nil];
  661. //[[NSNotificationCenter defaultCenter] postNotificationName:RefreshNotification object:nil userInfo:nil];
  662. // [[NSNotificationCenter defaultCenter] postNotificationName:IAPHelperProductPurchasedNotification object:nil userInfo:nil];
  663.  
  664. /*
  665. [buttonsArray removeAllObjects];
  666. sleep(2);
  667. [_myCollectionView reloadInputViews];
  668. [_myCollectionView reloadData];
  669. */
  670.  
  671. // Compra concluída com sucesso
  672. // interactVar = 2;
  673. // [[NSNotificationCenter defaultCenter] postNotificationName:@"interactWithUI" object:nil userInfo:nil];
  674. }
  675.  
  676. -(void)errorWithTransaction:(SKPaymentTransaction *)transaction {
  677. [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
  678. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Compra"
  679. message:@"Falhou"
  680. delegate:nil
  681. cancelButtonTitle:@"Fechar"
  682. otherButtonTitles:nil];
  683. [alert show];
  684. }
  685.  
  686. -(void)checkReceipt:(NSData *)receipt {
  687.  
  688.  
  689. NSString *receiptStorageFile = [DocumentsDirectory stringByAppendingPathComponent:@"receiptsIssues.plist"];
  690. NSMutableArray *receiptStorage = [[NSMutableArray alloc] initWithContentsOfFile:receiptStorageFile];
  691. if(!receiptStorage) {
  692. receiptStorage = [[NSMutableArray alloc] init];
  693. }
  694. [receiptStorage addObject:receipt];
  695. [receiptStorage writeToFile:receiptStorageFile atomically:YES];
  696.  
  697. [ReceiptCheck validateReceiptWithData:receipt completionHandler:^(BOOL success,NSString *answer){
  698. NSError *jsonError = nil;
  699. NSData *JSONdata = [answer dataUsingEncoding:NSUTF8StringEncoding];
  700. NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:JSONdata options:0 error:&jsonError];
  701.  
  702. NSDictionary *receipt = [dic objectForKey:@"receipt"];
  703. NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
  704.  
  705.  
  706. if([SixMonths isEqualToString:[receipt objectForKey:@"product_id"]]
  707. || [OneYear isEqualToString:[receipt objectForKey:@"product_id"]]
  708. || [ThreeMonths isEqualToString:[receipt objectForKey:@"product_id"]]
  709. || [OneMonth isEqualToString:[receipt objectForKey:@"product_id"]]
  710. || [Week isEqualToString:[receipt objectForKey:@"product_id"]]
  711. ){
  712. [prefs setObject: [receipt objectForKey:@"expires_date_formatted"] forKey:@"expires_date_formatted"];
  713. [prefs setObject: [receipt objectForKey:@"purchase_date"] forKey:@"purchase_date"];
  714. [prefs setObject: [receipt objectForKey:@"product_id"] forKey:@"product_id"];
  715.  
  716.  
  717. }else{
  718. NSMutableArray *bundles;
  719. if([prefs objectForKey:@"bundle"]==nil)
  720. bundles = [[NSMutableArray alloc]init];
  721. else
  722. bundles = [[prefs objectForKey:@"bundle"] mutableCopy];
  723.  
  724. @try {
  725. [bundles addObject:[receipt objectForKey:@"product_id"]];
  726. [prefs setObject:bundles forKey:@"bundle"];
  727. }
  728. @catch (NSException *exception) {
  729. NSLog(@"%@",exception);
  730. NSLog(@"deu merda ta claro");
  731. }
  732. }
  733.  
  734.  
  735. if(success==YES)
  736. {
  737. [self fastIssueBuyitSave:answer];
  738. NSLog(@"Receipt has been validated: %@",answer);
  739.  
  740. } else {
  741. NSLog(@"Receipt not validated! Error: %@",answer);
  742. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Erro na compra" message:@"Não foi possivel validar o pagamento" delegate:nil cancelButtonTitle:@"Fechar" otherButtonTitles:nil];
  743. [alert show];
  744. };
  745. }];
  746. }
  747.  
  748. -(void)fastIssueBuyitSave:(NSString *)message{
  749.  
  750. NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
  751. issuesBuyit = [[defaults objectForKey:@"issuesBuyit"]mutableCopy];
  752. if(issuesBuyit == nil)
  753. issuesBuyit = [[NSMutableArray alloc] init];
  754.  
  755. NSError *jsonError = nil;
  756. NSData *JSONdata = [message dataUsingEncoding:NSUTF8StringEncoding];
  757. NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:JSONdata options:0 error:&jsonError];
  758.  
  759. NSDictionary *receipt = [dic objectForKey:@"receipt"];
  760. [issuesBuyit addObject:[NSString stringWithFormat:@"%@",[receipt objectForKey:@"product_id"]]];
  761. [defaults setObject:issuesBuyit forKey:@"issuesBuyit"];
  762. [defaults synchronize];
  763.  
  764. }
  765.  
  766.  
  767.  
  768.  
  769. #pragma mark - Check all saved receipts
  770. -(int)checkReceipts:(NSString *)date{
  771. // open receipts
  772. ret=0;
  773. NSArray *receipts = [[NSArray alloc] initWithContentsOfFile:[DocumentsDirectory stringByAppendingPathComponent:@"receiptsIssues.plist"]];
  774. if(!receipts || [receipts count]==0) {
  775. // NSLog(@"ViewController.m : checkReceipts / No receiptsIssues.plist file found");
  776. return 0;
  777. }
  778.  
  779. NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
  780. if(![prefs objectForKey:@"product_id"])
  781. {
  782. // NSLog(@"ViewController.m : checkReceipts / No prefs:objectForKey:product_id found");
  783. return 0;
  784. }
  785.  
  786.  
  787. NSLog(@"ViewController.m : checkReceipts / purchase_date = %@",[prefs objectForKey:@"purchase_date"]);
  788. NSLog(@"ViewController.m : checkReceipts / expires_dat_formatted = %@",[prefs objectForKey:@"expires_date_formatted"]);
  789. if([self dateBetweenDates:[prefs objectForKey:@"purchase_date"] :[prefs objectForKey:@"expires_date_formatted"]:date])
  790. {
  791. NSLog(@"ViewController.m : checkReceipts / InApp Purchase OK");
  792. return 1;
  793. }
  794.  
  795. NSLog(@"ViewController.m : checkReceipts / No InApp Purchase found");
  796. return 0;
  797. }
  798.  
  799.  
  800. -(int)checkBundleList:(NSString *)bundle{
  801.  
  802. NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
  803. issuesBuyit = [[defaults objectForKey:@"issuesBuyit"] mutableCopy];
  804. for(int i = 0; i < [issuesBuyit count];i++){
  805. if([bundle isEqualToString:[issuesBuyit objectAtIndex:i]])
  806. return 1;
  807. }
  808. return 0;
  809. }
  810.  
  811.  
  812. -(void)reload{
  813. /* [buttonsArray removeAllObjects];
  814. sleep(5);
  815.  
  816. [_myCollectionView reloadInputViews];
  817. [_myCollectionView reloadData];*/
  818.  
  819. // [self performSelectorInBackground:@selector(reload2) withObject:nil];
  820. }
  821.  
  822. -(void)reload2{
  823. /* [buttonsArray removeAllObjects];
  824. sleep(5);
  825. [_myCollectionView reloadInputViews];
  826. [_myCollectionView reloadData];*/
  827. }
  828.  
  829. -(BOOL)dateBetweenDates:(NSString *)dateSrt{
  830. NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
  831. NSDateFormatter *df=[[NSDateFormatter alloc]init];
  832.  
  833.  
  834. NSString *aux = [NSString stringWithFormat:@"%@",dateSrt];
  835. NSArray *fields = [aux componentsSeparatedByString:@" "];
  836.  
  837.  
  838.  
  839.  
  840.  
  841. df.dateFormat = @"yyyy-MM-dd";
  842. NSDate *today = [df dateFromString:[fields objectAtIndex:0]];
  843. NSDate *dateInicio = [df dateFromString:[prefs objectForKey:@"data_inicio"]];
  844. NSDate *dateFim = [df dateFromString:[prefs objectForKey:@"data_fim"]];
  845.  
  846.  
  847.  
  848. NSComparisonResult resultInicio,resultFim;
  849. resultInicio = [today compare:dateInicio];
  850. resultFim = [today compare:dateFim];
  851.  
  852.  
  853.  
  854. if((resultInicio == NSOrderedDescending && resultFim == NSOrderedAscending) || resultInicio == NSOrderedSame || resultFim == NSOrderedSame)
  855. return true;
  856. else
  857. return false;
  858.  
  859. }
  860.  
  861. -(BOOL)dateBetweenDates:(NSString *)dateBegin:(NSString *)dateEnd:(NSString *)issue{
  862. NSDateFormatter *df=[[NSDateFormatter alloc]init];
  863. df.dateFormat = @"yyyy-MM-dd";
  864.  
  865.  
  866.  
  867. NSString *aux = [NSString stringWithFormat:@"%@",dateBegin];
  868. NSArray *fields = [aux componentsSeparatedByString:@" "];
  869.  
  870. NSString *aux2 = [NSString stringWithFormat:@"%@",dateEnd];
  871. NSArray *fields2 = [aux2 componentsSeparatedByString:@" "];
  872.  
  873. NSString *aux3= [NSString stringWithFormat:@"%@",issue];
  874. NSArray *fields3 = [aux3 componentsSeparatedByString:@" "];
  875.  
  876. NSDate *min = [df dateFromString:[fields objectAtIndex:0]];
  877. NSDate *max = [df dateFromString:[fields2 objectAtIndex:0]];
  878.  
  879. //NSDate *min = [df dateFromString:@"2013-01-03"];
  880. //NSDate *max = [df dateFromString:@"2013-09-09"];
  881.  
  882. NSDate *today = [df dateFromString:[fields3 objectAtIndex:0]];
  883. NSComparisonResult resultInicio,resultFim;
  884. resultInicio = [today compare:min]; //Same
  885. resultFim = [today compare:max];//Descending
  886.  
  887. if((resultInicio == NSOrderedDescending && resultFim == NSOrderedAscending) || resultFim == NSOrderedSame || resultInicio == NSOrderedSame)
  888. return true;
  889. else
  890. return false;
  891. }
  892.  
  893.  
  894.  
  895. -(void)refreshLogin{
  896. interactVar = 5;
  897. [[NSNotificationCenter defaultCenter] postNotificationName:@"interactWithUI" object:nil userInfo:nil];
  898. }
  899.  
  900.  
  901. -(void)Reachability{
  902.  
  903.  
  904.  
  905. Reachability *internetReachableFoo;
  906.  
  907. internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"];
  908.  
  909. // Internet is reachable
  910. internetReachableFoo.reachableBlock = ^(Reachability*reach)
  911. {
  912. // Update the UI on the main thread
  913. dispatch_async(dispatch_get_main_queue(), ^{
  914. haveNet= true;
  915. });
  916. };
  917.  
  918. // Internet is not reachable
  919. internetReachableFoo.unreachableBlock = ^(Reachability*reach)
  920. {
  921. // Update the UI on the main thread
  922. dispatch_async(dispatch_get_main_queue(), ^{
  923. haveNet= false;
  924. });
  925. };
  926.  
  927. [internetReachableFoo startNotifier];
  928.  
  929. }
  930.  
  931. -(void)SetBanner{
  932.  
  933.  
  934.  
  935. if(haveNet){
  936.  
  937.  
  938. NSString *device = [[UIDevice currentDevice] model];
  939. NSURL *url;
  940. NSString *myString;
  941. @try {
  942. int count =0;
  943.  
  944. do {
  945. sleep(1);
  946. UIInterfaceOrientation orientation= [[UIApplication sharedApplication] statusBarOrientation];
  947.  
  948. if([device isEqualToString:@"iPad"]&& UIInterfaceOrientationIsLandscape(orientation))
  949. url = [[NSURL alloc] initWithString:[JsonPost shareGlobalData].ipadL];
  950. else if([device isEqualToString:@"iPad"]&& UIInterfaceOrientationIsPortrait(orientation))
  951. url = [[NSURL alloc] initWithString:[JsonPost shareGlobalData].ipadP];
  952. else if([device isEqualToString:@"iPhone"]&& UIInterfaceOrientationIsLandscape(orientation))
  953. url = [[NSURL alloc] initWithString:[JsonPost shareGlobalData].iphoneL];
  954. else if([device isEqualToString:@"iPhone"]&& UIInterfaceOrientationIsPortrait(orientation))
  955. url = [[NSURL alloc] initWithString:[JsonPost shareGlobalData].iphoneP];
  956. else
  957. url = [[NSURL alloc] initWithString:[JsonPost shareGlobalData].ipadL];
  958. count++;
  959.  
  960. myString = [url absoluteString];
  961.  
  962. } while ([myString isEqualToString:@"NIL"]|| count ==3); //tenta 10x no maximo até ter o url
  963.  
  964. NSData * imageData = [NSData dataWithContentsOfURL:url];
  965. UIImage * image = [UIImage imageWithData:imageData];
  966. _banner.image = image;
  967. }
  968. @catch (NSException *exception) {
  969.  
  970.  
  971. NSLog(@"Crach why -> %@",exception);
  972. NSLog(@"[SLf] ViewController :: SetBanner crashed...");
  973. }
  974.  
  975. }
  976. // Enable the menu
  977. //[_loadingActivity stopAnimating];
  978. // _loadingActivity.hidden = TRUE;
  979. _pleaseWaitWindow.hidden = true;
  980. _barButton.enabled = YES;
  981. }
  982.  
  983. -(void)loadBanner{
  984.  
  985. }
  986.  
  987. - (void)viewDidUnload {
  988. [self setBanner:nil];
  989. [super viewDidUnload];
  990. }
  991. - (IBAction)bannerPressed:(id)sender {
  992.  
  993.  
  994. @try {
  995. NSString *url = [JsonPost shareGlobalData].bannerURL;
  996. url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  997. [[UIApplication sharedApplication]openURL:[NSURL URLWithString:url]];
  998. }
  999. @catch (NSException *exception) {
  1000. NSLog(@"Fudeu-se");
  1001. }
  1002.  
  1003.  
  1004.  
  1005. }
  1006.  
  1007. -(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
  1008.  
  1009. if(toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight){
  1010.  
  1011.  
  1012. _myCollectionView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
  1013. [[self navigationController] setNavigationBarHidden:YES];
  1014. }
  1015. else{
  1016. [[self navigationController] setNavigationBarHidden:NO];
  1017. }
  1018. [self SetBanner];
  1019.  
  1020. }
  1021.  
  1022.  
  1023.  
  1024. - (void)Restore {
  1025.  
  1026. [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
  1027.  
  1028.  
  1029. NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
  1030.  
  1031.  
  1032. NSArray *receipts = [[NSArray alloc] initWithContentsOfFile:[DocumentsDirectory stringByAppendingPathComponent:@"receiptsIssues.plist"]];
  1033. if(!receipts || [receipts count]==0) {
  1034.  
  1035. return;
  1036. }
  1037.  
  1038. for(NSData *aReceipt in receipts) {
  1039. [ReceiptCheck validateReceiptWithData:aReceipt completionHandler:^(BOOL success, NSString *message) {
  1040. NSError *jsonError = nil;
  1041. NSData *JSONdata = [message dataUsingEncoding:NSUTF8StringEncoding];
  1042. NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:JSONdata options:0 error:&jsonError];
  1043.  
  1044. NSDictionary *receipt = [dic objectForKey:@"receipt"];
  1045.  
  1046.  
  1047. if([SixMonths isEqualToString:[receipt objectForKey:@"product_id"]])
  1048. [prefs setObject:SixMonths forKey:@"Subscription"];
  1049. else if([OneYear isEqualToString:[receipt objectForKey:@"product_id"]])
  1050. [prefs setObject:OneYear forKey:@"Subscription"];
  1051. else if([OneMonth isEqualToString:[receipt objectForKey:@"product_id"]])
  1052. [prefs setObject:OneMonth forKey:@"Subscription"];
  1053. else if([Week isEqualToString:[receipt objectForKey:@"product_id"]])
  1054. [prefs setObject:Week forKey:@"Subscription"];
  1055. else if([ThreeMonths isEqualToString:[receipt objectForKey:@"product_id"]])
  1056. [prefs setObject:ThreeMonths forKey:@"Subscription"];
  1057.  
  1058.  
  1059. }
  1060. ];
  1061. }
  1062.  
  1063. }
  1064.  
  1065.  
  1066.  
  1067. @end
Add Comment
Please, Sign In to add comment