Guest User

Untitled

a guest
Aug 3rd, 2017
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 44.82 KB | None | 0 0
  1. //
  2. // ChatMessagesVC.m
  3. // Chat21
  4. //
  5. // Created by Dario De Pascalis on 22/03/16.
  6. // Copyright © 2016 Frontiere21. All rights reserved.
  7. //
  8.  
  9. #import "ChatMessagesVC.h"
  10.  
  11. //#import "MessagesViewController.h"
  12. #import "ChatMessage.h"
  13. #import "SHPUser.h"
  14. #import "ChatUtil.h"
  15. #import "ChatDB.h"
  16. #import "ChatConversation.h"
  17. #import "SHPApplicationContext.h"
  18. #import "ChatManager.h"
  19. #import "ChatConversationHandler.h"
  20. #import "SHPConversationsVC.h"
  21. #import "SHPImageDownloader.h"
  22. #import "SHPImageUtil.h"
  23. #import "SHPStringUtil.h"
  24. #import "GroupInfoVC.h"
  25. #import "QBPopupMenu.h"
  26. #import "QBPopupMenuItem.h"
  27. #import "SHPHomeProfileTVC.h"
  28. #import "ChatTitleVC.h"
  29. #import "ChatImageCache.h"
  30. #import "ChatImageWrapper.h"
  31. #import "ChatMessagesTVC.h"
  32. #import "ChatGroup.h"
  33. #import "ChatStatusTitle.h"
  34. #import <DropboxSDK/DropboxSDK.h>
  35. #import <DBChooser/DBChooser.h>
  36.  
  37. @interface ChatMessagesVC (){
  38. SystemSoundID soundID;
  39. }
  40. @end
  41.  
  42. @implementation ChatMessagesVC
  43.  
  44. //int MAX_WIDTH_TEXTCHAT = 230;//250.0;
  45. //int WIDTH_BOX_DATE = 50.0;
  46.  
  47.  
  48. - (void)viewDidLoad {
  49. [super viewDidLoad];
  50. NSLog(@"Loading messages...");
  51. keyboardShow = NO;//GESTIONE KEYBOARD
  52. if (self.recipient) {
  53. self.recipientFullname ? [self customizeTitle:self.recipientFullname] : [self customizeTitle:self.recipient];
  54. } else {
  55. NSString *title = self.group.name;
  56. [self customizeTitle:title];
  57. }
  58.  
  59. SHPUser *me = self.applicationContext.loggedUser;
  60. self.senderId = [me.username stringByReplacingOccurrencesOfString:@"." withString:@"_"];
  61. [self registerForKeyboardNotifications];
  62. [self backgroundTapToDismissKB:YES];
  63.  
  64. [self initConversationHandler];
  65. originalViewHeight = self.view.bounds.size.height;
  66. heightTable = 0;// self.tableView.bounds.size.height;
  67. self.bottomReached = YES;
  68.  
  69. // MENU
  70. [self setupLabels];
  71. [self initImageCache];
  72. // [self popUpMenu];
  73. [self buildUnreadBadge];
  74. [self setupConnectionStatus];
  75. if (!self.group) {
  76. [self setupOnlineStatus];
  77. }
  78. if (self.group) {
  79. [self writeBoxEnabled];
  80. }
  81. }
  82.  
  83. -(void)writeBoxEnabled {
  84. NSLog(@"can I write in this group?");
  85. if (!self.group) {
  86. return;
  87. }
  88. NSString *my_user_id = self.applicationContext.loggedUser.username;
  89. NSString *firebase_sanitized_userid = [my_user_id stringByReplacingOccurrencesOfString:@"." withString:@"_"];
  90. NSDictionary *members = self.group.members;
  91.  
  92. NSString *user_found = [members objectForKey:firebase_sanitized_userid];
  93. user_found ? [self hideBottomView:NO] : [self hideBottomView:YES];
  94. }
  95.  
  96. -(void)hideBottomView:(BOOL)hide {
  97. if (hide) {
  98. NSLog(@"Hide write box");
  99. self.bottomView.hidden = YES;
  100. self.bottomViewHeightConstraint.constant = 0.0;
  101. } else {
  102. NSLog(@"Show write box");
  103. self.bottomView.hidden = NO;
  104. self.bottomViewHeightConstraint.constant = 44.0;
  105. }
  106. }
  107. -(void)viewWillAppear:(BOOL)animated {
  108. [super viewWillAppear:animated];
  109. self.tabBarController.tabBar.hidden=YES;
  110. //[self.tableView reloadData];
  111. }
  112.  
  113. -(void)viewDidAppear:(BOOL)animated {
  114. [super viewDidAppear:animated];
  115. if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
  116. self.navigationController.interactivePopGestureRecognizer.delegate = self;
  117. }
  118. [self updateUnreadMessagesCount];
  119. if (self.textToSendAsChatOpens) {
  120. [self sendMessage:self.textToSendAsChatOpens attributes:self.attributesToSendAsChatOpens];
  121. self.textToSendAsChatOpens = nil;
  122. self.attributesToSendAsChatOpens = nil;
  123. [self.messageTextField becomeFirstResponder];
  124. }
  125. }
  126.  
  127.  
  128. -(void)viewWillDisappear:(BOOL)animated {
  129. NSLog(@"VIEW WILL DISAPPEAR... %@", self);
  130. [super viewWillDisappear:animated];
  131. [self dismissKeyboard];
  132. [self removeUnreadBadge];
  133. if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
  134. self.navigationController.interactivePopGestureRecognizer.delegate = nil;
  135. }
  136. if (self.isMovingFromParentViewController) {
  137. NSLog(@"isMovingFromParentViewController: OK");
  138. [self resetTitleView];
  139. self.tabBarController.tabBar.hidden=NO;
  140. self.conversationHandler.delegateView = nil;
  141. self.conversationsVC = nil;
  142. for (NSString *k in self.imageDownloadsInProgress) {
  143. NSLog(@"Removing downloader: %@", k);
  144. SHPImageDownloader *iconDownloader = [self.imageDownloadsInProgress objectForKey:k];
  145. [iconDownloader cancelDownload];
  146. iconDownloader.delegate = nil;
  147. }
  148. NSLog(@"Removing Firebase references...");
  149. [self.connectedRef removeObserverWithHandle:self.connectedRefHandle];
  150. [self.onlineRef removeObserverWithHandle:self.online_ref_handle];
  151. [self.lastOnlineRef removeObserverWithHandle:self.last_online_ref_handle];
  152. }
  153. }
  154.  
  155. // TIP: why this method? http://www.yichizhang.info/2015/03/02/prescroll-a-uitableview.html
  156. -(void)viewDidLayoutSubviews {
  157. [super viewDidLayoutSubviews];
  158. [containerTVC scrollToLastMessage:NO];
  159. }
  160.  
  161. //---------------------------------------------------//
  162. //START FUNCTIONS
  163. //---------------------------------------------------//
  164. -(void)setContainer {
  165. containerTVC = [self.childViewControllers objectAtIndex:0];
  166. containerTVC.vc = self;
  167. containerTVC.conversationHandler = self.conversationHandler;
  168. [containerTVC reloadDataTableView];
  169. }
  170.  
  171.  
  172. -(void)setupLabels {
  173. [self.sendButton setTitle:NSLocalizedString(@"ChatSend", nil) forState:UIControlStateNormal];
  174. self.messageTextField.placeholder = NSLocalizedString(@"digit message", nil);
  175. }
  176.  
  177. -(void)initImageCache {
  178. // cache setup
  179. self.imageCache = (ChatImageCache *) [self.applicationContext getVariable:@"chatUserIcons"];
  180. if (!self.imageCache) {
  181. self.imageCache = [[ChatImageCache alloc] init];
  182. self.imageCache.cacheName = @"chatUserIcons";
  183. [self.applicationContext setVariable:@"chatUserIcons" withValue:self.imageCache];
  184. }
  185. }
  186.  
  187. // ************************
  188. // *** ONLINE / OFFLINE ***
  189. // ************************
  190.  
  191.  
  192. -(void)setupConnectionStatus {
  193. // initial status UI
  194. [self unconnectedStatus];
  195.  
  196. // ChatManager *chat = [ChatManager getSharedInstance];
  197. NSString *url = @"/.info/connected";
  198. FIRDatabaseReference *rootRef = [[FIRDatabase database] reference];
  199. self.connectedRef = [rootRef child:url];
  200. self.connectedRefHandle = [self.connectedRef observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot) {
  201. if([snapshot.value boolValue]) {
  202. NSLog(@"connected");
  203. [self connectedStatus];
  204. } else {
  205. NSLog(@"not connected");
  206. [self unconnectedStatus];
  207. }
  208. }];
  209. }
  210.  
  211. -(void)connectedStatus {
  212. self.usernameButton.hidden = NO;
  213. self.activityIndicator.hidden = YES;
  214. self.sendButton.enabled = YES;
  215. [self.activityIndicator stopAnimating];
  216. if (self.group) {
  217. self.statusLabel.text = [ChatUtil groupMembersAsStringForUI:self.group.members]; //NSLocalizedString(@"group summary", nil);
  218. } else {
  219. [self onlineStatus];
  220. }
  221. }
  222.  
  223. -(void)unconnectedStatus {
  224. self.usernameButton.hidden = YES;
  225. self.activityIndicator.hidden = NO;
  226. self.sendButton.enabled = NO;
  227. [self.activityIndicator startAnimating];
  228. self.statusLabel.text = NSLocalizedString(@"ChatDisconnected", nil);
  229. }
  230.  
  231. -(void)onlineStatus {
  232. if (self.online) {
  233. NSLog(@"WELL CONNECTED. AND ONLINE!");
  234. self.statusLabel.text = NSLocalizedString(@"online", nil);
  235. } else {
  236. NSLog(@"WELL CONNECTED. BUT OFFLINE!");
  237. NSString *last_online_status;
  238. if (self.lastOnline) {
  239. NSString *last_seen = NSLocalizedString(@"last seen", nil);
  240. NSString *short_date = [SHPStringUtil timeFromNowToString:self.lastOnline];
  241. last_online_status = [[NSString alloc] initWithFormat:@"%@ %@",last_seen, short_date];
  242. } else {
  243. last_online_status = NSLocalizedString(@"offline", nil);
  244. }
  245. self.statusLabel.text = last_online_status;
  246. }
  247. }
  248.  
  249. -(void)setupOnlineStatus {
  250. ChatManager *chat = [ChatManager getSharedInstance];
  251. ChatPresenceHandler *handler = chat.presenceHandler;
  252. if (!handler) {
  253. NSLog(@"Presence Handler not correctly initialized.");
  254. return;
  255. }
  256.  
  257. // IS ONLINE?
  258. // Since user can connect from multiple devices, we store each connection instance separately.
  259. // Any time that connectionsRef's value is null (i.e. has no children) the user is offline
  260.  
  261. self.onlineRef = [handler onlineRefForUser:[self.recipient stringByReplacingOccurrencesOfString:@"." withString:@"_"]];
  262. NSLog(@"online ref: %@", self.onlineRef);
  263. self.online_ref_handle = [self.onlineRef observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot) {
  264. if(snapshot.exists) {
  265. NSLog(@"ONLINE: %@", snapshot);
  266. self.online = YES;
  267. [self onlineStatus];
  268. } else {
  269. NSLog(@"OFFLINE: %@", snapshot);
  270. self.online = NO;
  271. [self onlineStatus];
  272. }
  273. }];
  274.  
  275. // LAST ONLINE
  276.  
  277. self.lastOnlineRef = [handler lastOnlineRefForUser:[self.recipient stringByReplacingOccurrencesOfString:@"." withString:@"_"]];
  278. NSLog(@"last online ref: %@", self.lastOnlineRef);
  279. self.last_online_ref_handle = [self.lastOnlineRef observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot) {
  280. NSLog(@"LAST ONLINE: %@", snapshot);
  281. [self snapshotDate:snapshot];
  282. [self onlineStatus];
  283. }];
  284. }
  285.  
  286. -(void)snapshotDate:(FIRDataSnapshot *)snapshot {
  287. if (!snapshot.exists) {
  288. return;
  289. }
  290. self.lastOnline = [NSDate dateWithTimeIntervalSince1970:[snapshot.value longValue]/1000];
  291. NSLog(@"LAST ONLINE DATE: %@", self.lastOnline);
  292. }
  293.  
  294.  
  295. // ************************
  296. // *** ONLINE / OFFLINE ***
  297. // ************************
  298. // ********* END **********
  299. // ************************
  300.  
  301.  
  302. -(void)buildUnreadBadge {
  303. self.unreadLabel = [[UILabel alloc] initWithFrame:CGRectMake(16, 4, 16, 16)];
  304. [self.unreadLabel setBackgroundColor:[UIColor redColor]];
  305. [self.unreadLabel setTextColor:[UIColor whiteColor]];
  306. self.unreadLabel.font = [UIFont systemFontOfSize:11];
  307. self.unreadLabel.textAlignment = NSTextAlignmentCenter;
  308. self.unreadLabel.layer.masksToBounds = YES;
  309. self.unreadLabel.layer.cornerRadius = 8.0;
  310. [self.navigationController.navigationBar addSubview:self.unreadLabel];
  311. self.unreadLabel.hidden = YES;
  312. }
  313.  
  314. -(void)updateUnreadMessagesCount {
  315. if (self.unread_count > 0) {
  316. self.unreadLabel.hidden = NO;
  317. self.unreadLabel.text = [[NSString alloc] initWithFormat:@"%d", self.unread_count];
  318. } else {
  319. self.unreadLabel.hidden = YES;
  320. }
  321. }
  322.  
  323. -(void)removeUnreadBadge {
  324. NSLog(@"Removing unread label... %@", self.unreadLabel);
  325. [self.unreadLabel removeFromSuperview];
  326. }
  327.  
  328. -(void)customizeTitle:(NSString *)title {
  329. self.navigationItem.title = title;
  330. self.navigationItem.titleView = nil;
  331.  
  332.  
  333. NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"status_title" owner:self options:nil];
  334. ChatStatusTitle *view = [subviewArray objectAtIndex:0];
  335. view.frame = CGRectMake(0, 0, 240, 40);
  336. self.usernameButton = view.usernameButton;
  337. self.statusLabel = view.statusLabel;
  338. self.activityIndicator = view.activityIndicator;
  339. [view.usernameButton setTitle:title forState:UIControlStateNormal];
  340. [view.usernameButton addTarget:self
  341. action:@selector(goToProfile:)
  342. forControlEvents:UIControlEventTouchUpInside];
  343. self.navigationItem.titleView = view;
  344.  
  345. // // VISTA
  346. // UIStoryboard *mystoryboard = [UIStoryboard storyboardWithName:@"Chat" bundle:nil];
  347. // self.titleVC = [mystoryboard instantiateViewControllerWithIdentifier:@"ChatTitle"];
  348. // UIView *view = self.titleVC.view;
  349. // view.frame = CGRectMake(0, 0, 200, 40);
  350. // NSLog(@"w %f h %f", view.frame.size.width, view.frame.size.height);
  351. // NSLog(@"vc.usernameButton %@ title %@", self.titleVC.usernameButton, title);
  352. // [self.titleVC.usernameButton setTitle:title forState:UIControlStateNormal];
  353. // [self.titleVC.usernameButton addTarget:self
  354. // action:@selector(goToProfile:)
  355. // forControlEvents:UIControlEventTouchUpInside];
  356. // self.usernameButton = self.titleVC.usernameButton;
  357. // self.statusLabel = self.titleVC.statusLabel;
  358. // self.activityIndicator = self.titleVC.activityIndicator;
  359. // self.navigationItem.titleView = self.titleVC.view;
  360. // // FINE VISTA
  361. }
  362.  
  363. -(void)resetTitleView {
  364. NSLog(@"RESETTING TITLE VIEW");
  365. self.usernameButton = nil;
  366. self.statusLabel = nil;
  367. self.activityIndicator = nil;
  368. self.navigationItem.titleView = nil;
  369. self.titleVC = nil;
  370. }
  371.  
  372. -(void)chatTitleButtonPressed {
  373. NSLog(@"title button pressed");
  374. }
  375.  
  376. -(void)goToProfile:(UIButton*)sender {
  377. //NSLog(@"goToProfile");
  378. // self.profileVC = (SHPHomeProfileTVC *)[self.applicationContext getVariable:@"profileVC"];
  379.  
  380. if (self.group) {
  381. [self performSegueWithIdentifier:@"GroupInfo" sender:self];
  382. } else {
  383. // if (!self.profileVC) {
  384. self.profileSB = [UIStoryboard storyboardWithName:@"Profile" bundle:nil];
  385. self.profileNC = [self.profileSB instantiateViewControllerWithIdentifier:@"navigationProfile"];
  386. SHPHomeProfileTVC *profileVC = (SHPHomeProfileTVC *)[[self.profileNC viewControllers] objectAtIndex:0];
  387. // }
  388. NSLog(@"storyb -------------->>>>>> %@", self.profileSB);
  389. NSString *username = self.recipient;
  390. profileVC.applicationContext = self.applicationContext;
  391. SHPUser *authorProfile = [[SHPUser alloc] init];
  392. authorProfile.username = username;
  393. // self.profileVC.user = authorProfile;
  394. profileVC.otherUser = authorProfile;
  395. NSLog(@"self.profileVC.otherUser %@", profileVC.otherUser.username);
  396. [self.navigationController pushViewController:profileVC animated:YES];
  397. }
  398. }
  399.  
  400.  
  401. //-(void)popUpMenu {
  402. // // QBPopupMenuItem *itemCopy = [QBPopupMenuItem itemWithTitle:@"Copicchia" target:self action:@selector(copicchia:)];
  403. // // // QBPopupMenuItem *item2 = [QBPopupMenuItem itemWithImage:[UIImage imageNamed:@"image"] target:self action:@selector(action:)];
  404. // // self.popupMenu = [[QBPopupMenu alloc] initWithItems:@[itemCopy]];
  405. //
  406. // QBPopupMenuItem *item_copy = [QBPopupMenuItem itemWithTitle:@"Copia" target:self action:@selector(copy_action:)];
  407. // QBPopupMenuItem *item_resend = [QBPopupMenuItem itemWithTitle:@"Copia" target:self action:@selector(resend_action:)];
  408. // QBPopupMenuItem *item_delete = [QBPopupMenuItem itemWithTitle:@"Copia" target:self action:@selector(delete_action:)];
  409. //
  410. // // QBPopupMenuItem *item5 = [QBPopupMenuItem itemWithImage:[UIImage imageNamed:@"clip"] target:self action:@selector(action)];
  411. // // QBPopupMenuItem *item6 = [QBPopupMenuItem itemWithTitle:@"Delete" image:[UIImage imageNamed:@"trash"] target:self action:@selector(action)];
  412. // NSArray *items = @[item_copy];
  413. //
  414. // QBPopupMenu *popupMenu = [[QBPopupMenu alloc] initWithItems:items];
  415. // popupMenu.highlightedColor = [[UIColor colorWithRed:0 green:0.478 blue:1.0 alpha:1.0] colorWithAlphaComponent:0.8];
  416. // popupMenu.height = 30;
  417. // popupMenu.navigationBarHeight = self.navigationController.navigationBar.frame.size.height;
  418. // popupMenu.statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
  419. // popupMenu.delegate = self;
  420. // self.popupMenu = popupMenu;
  421. //}
  422. //
  423. //-(void)popupMenuDidDisappear:(QBPopupMenu *)menu {
  424. // [self backgroundTapToDismissKB:YES];
  425. //}
  426. //
  427. //-(void)copy_action:(id)sender {
  428. // UIPasteboard *generalPasteboard = [UIPasteboard generalPasteboard];
  429. // generalPasteboard.string = self.selectedText;
  430. // NSLog(@"Text copied!");
  431. //}
  432. //
  433. //- (void)longPressOnCellGestureRecognizer:(UIGestureRecognizer *)recognizer
  434. //{
  435. // NSLog(@"LONG PRESS!!!!!");
  436. //
  437. // if (recognizer.state == UIGestureRecognizerStateBegan) {
  438. // NSLog(@"Action");
  439. // [self showCustomPopupMenu:recognizer];
  440. // }
  441. //}
  442. //
  443. //-(void)showCustomPopupMenu:(UIGestureRecognizer *)recognizer {
  444. //// CGPoint pressLocation = [recognizer locationInView:self.tableView];
  445. //// NSIndexPath *pressIndexPath = [self.tableView indexPathForRowAtPoint:pressLocation];
  446. //// UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:pressIndexPath];
  447. //// UILabel *message_label = (UILabel *)[cell viewWithTag:3];
  448. //// self.selectedText = message_label.text;
  449. //// UIView *sfondo_cella = (UIView *)[cell viewWithTag:100];
  450. //// NSLog(@"msg: %@", message_label.text);
  451. //// CGFloat abs_x = sfondo_cella.frame.origin.x + cell.frame.origin.x + self.view.frame.origin.x; // l'ultimo è zero
  452. //// CGRect rectInTableView = [self.tableView rectForRowAtIndexPath:pressIndexPath];
  453. //// CGRect rectInSuperview = [self.tableView convertRect:rectInTableView toView:[self.tableView superview]];
  454. //// CGFloat abs_y = rectInSuperview.origin.y + sfondo_cella.frame.origin.y;
  455. //// NSLog(@"abs_y %f", abs_y);
  456. //// // absolute to view, not tableView
  457. //// CGRect absolute_to_view_rect = CGRectMake(abs_x, abs_y, message_label.frame.size.width, message_label.frame.size.height);
  458. //// // disable keyboard's gesture recognizer
  459. //// [self backgroundTapToDismissKB:NO];
  460. //// [self.popupMenu showInView:self.tableView targetRect:absolute_to_view_rect animated:YES];
  461. //// // test
  462. //// // CGRect targetRect = absolute_to_view_rect;
  463. //// // UIView *targetV = [[UIView alloc] initWithFrame:targetRect];
  464. //// // [targetV setBackgroundColor:[UIColor blueColor]];
  465. //// NSLog(@"VIEW %@", self.view);
  466. //// NSLog(@"TABLEVIEW %@", self.tableView);
  467. //// // [self.view addSubview:targetV];
  468. //// // [self.view addSubview:targetV];
  469. //// // NSLog(@"frame %f %f %f %f", targetRect.origin.x, targetRect.origin.y, targetRect.size.width, targetRect.size.height);
  470. //// // CGRect targetRect2 = CGRectMake(44, 268, 100, 40);
  471. //// // UIView *targetV2 = [[UIView alloc] initWithFrame:targetRect2];
  472. //// // [targetV2 setBackgroundColor:[UIColor redColor]];
  473. //// // [self.tableView addSubview:targetV2];
  474. //// // test end
  475. //}
  476.  
  477. //-(void)mainMenu {
  478. // // init the action menu
  479. // NSString *groupInfoButtonTitle = nil;
  480. // if (self.groupId) {
  481. // NSLog(@"MENU GROUP ON...");
  482. // if (self.groupId) {
  483. // groupInfoButtonTitle = @"Info gruppo";
  484. // }
  485. // }
  486. // // else {
  487. // // NSLog(@"MENU OFF");
  488. // // self.menuButton.enabled = NO;
  489. // // self.menuButton.tintColor = [UIColor clearColor];
  490. // // }
  491. // NSString *sendImageButtonTitle = @"Invia immagine";
  492. // if (groupInfoButtonTitle) {
  493. // self.menuSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"CancelLKey", nil) destructiveButtonTitle:nil otherButtonTitles:groupInfoButtonTitle, sendImageButtonTitle, nil];
  494. // }
  495. // else {
  496. // self.menuSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"CancelLKey", nil) destructiveButtonTitle:nil otherButtonTitles:sendImageButtonTitle, nil];
  497. // }
  498. // self.menuSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
  499. //
  500. // self.menuButton.enabled = YES;
  501. // self.menuButton.tintColor = nil;
  502. //}
  503. //
  504. //-(void)photoMenu {
  505. // // init the photo action menu
  506. // NSString *takePhotoButtonTitle = @"Scatta foto";
  507. // NSString *chooseExistingButtonTitle = @"Scegli dalla galleria";
  508. //
  509. // self.photoMenuSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"CancelLKey", nil) destructiveButtonTitle:nil otherButtonTitles:takePhotoButtonTitle, chooseExistingButtonTitle, nil];
  510. // self.photoMenuSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
  511. //}
  512.  
  513.  
  514.  
  515. - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
  516. {
  517. return NO;
  518. }
  519.  
  520. -(void)initConversationHandler {
  521. ChatManager *chat = [ChatManager getSharedInstance];
  522. ChatConversationHandler *handler = [chat getConversationHandlerByConversationId:self.conversationId];
  523. if (!handler) {
  524. NSLog(@"Conversation Handler not found. Creating & initializing a new one with conv-id %@", self.conversationId);
  525. // GROUP_MOD
  526. if (self.recipient) {
  527. handler = [[ChatConversationHandler alloc] initWithRecipient:self.recipient conversationId:self.conversationId user:self.applicationContext.loggedUser];
  528. } else {
  529. NSLog(@"*** CONVERSATION HANDLER IN GROUP MOD!!!!!!!");
  530. handler = [[ChatConversationHandler alloc] initWithGroupId:self.group.groupId conversationId:self.conversationId user:self.applicationContext.loggedUser];
  531. }
  532.  
  533. [chat addConversationHandler:handler];
  534. handler.delegateView = self;
  535. self.conversationHandler = handler;
  536.  
  537. // db
  538. NSLog(@"Restoring DB archived conversations.");
  539. [self.conversationHandler restoreMessagesFromDB];
  540. NSLog(@"Archived messages count %lu", (unsigned long)self.conversationHandler.messages.count);
  541.  
  542. NSLog(@"Connecting handler to firebase.");
  543. [self.conversationHandler connect];
  544. NSLog(@"Handler ref: %@", handler.messagesRef);
  545. NSLog(@"Adding new handler %@ to Conversations Manager.", handler);
  546. } else {
  547. handler.delegateView = self;
  548. self.conversationHandler = handler;
  549. }
  550. [self setContainer];
  551. }
  552.  
  553.  
  554. -(void)didFinishInitConversationHandler:(ChatConversationHandler *)handler error:(NSError *)error {
  555. if (!error) {
  556. NSLog(@"ChatConversationHandler Initialization finished with success.");
  557. } else {
  558. NSLog(@"ChatConversationHandler Initialization finished with error: %@", error);
  559. }
  560. }
  561. //---------------------------------------------------//
  562. //START FUNCTIONS
  563. //---------------------------------------------------//
  564.  
  565. //---------------------------------------------------//
  566. //INIZIO GESTIONE KEYBOARD
  567. //---------------------------------------------------//
  568. -(void)backgroundTapToDismissKB:(BOOL)activate
  569. {
  570. if (activate) {
  571. if (!self.tapToDismissKB) {
  572. self.tapToDismissKB = [[UITapGestureRecognizer alloc]
  573. initWithTarget:self
  574. action:@selector(dismissKeyboard)];
  575. self.tapToDismissKB.cancelsTouchesInView = YES;// without this, tap on buttons is captured by the view
  576. }
  577. [self.view addGestureRecognizer:self.tapToDismissKB];
  578. } else if (self.tapToDismissKB) {
  579. [self.view removeGestureRecognizer:self.tapToDismissKB];
  580. }
  581.  
  582. }
  583.  
  584. - (IBAction)addContentAction:(id)sender {
  585. NSLog(@"TEST DROPBOX ON THE FLY");
  586. // if (![[DBSession sharedSession] isLinked]) {
  587. // [[DBSession sharedSession] linkFromController:self];
  588. // }
  589. [[DBChooser defaultChooser] openChooserForLinkType:DBChooserLinkTypePreview
  590. fromViewController:self completion:^(NSArray *results)
  591. {
  592. if ([results count]) {
  593. // Process results from Chooser
  594. // NSLog(@"results %@", results);
  595. DBChooserResult *r = results[0];
  596. // NSLog(@"r.name %@", r.name);
  597. // NSLog(@"r.link %@", r.link);
  598. // NSLog(@"r.size %lld", r.size);
  599. // NSLog(@"r.iconURL %@", r.iconURL);
  600. NSDictionary *thumbs = r.thumbnails;
  601. // if (thumbs) {
  602. // NSArray*keys=[thumbs allKeys];
  603. // for (NSObject *k in keys) {
  604. // NSLog(@"r.thumb[%@]: %@", k, thumbs[k]);
  605. // }
  606. // NSLog(@"r.thumbs.64x64px %@", thumbs[@"64x64"]);
  607. // NSLog(@"r.thumbs.200x200px %@", thumbs[@"200x200"]);
  608. // NSLog(@"r.thumbs.640x480px %@", thumbs[@"640x480"]);
  609. // } else {
  610. // NSLog(@"No r.thumbs");
  611. // }
  612. [self sendDropboxMessage:r.name link:[r.link absoluteString] size:[NSNumber numberWithLongLong:r.size] iconURL:[r.iconURL absoluteString] thumbs:thumbs];
  613. } else {
  614. // User canceled the action
  615. NSLog(@"Action canceled");
  616. }
  617. }];
  618. }
  619.  
  620. -(void)dismissKeyboardFromTableView:(BOOL)activated {
  621. // NSLog(@"DISMISSING");
  622. [self backgroundTapToDismissKB:activated];
  623. }
  624.  
  625. -(void)dismissKeyboard {
  626. // NSLog(@"dismissing keyboard");
  627. [self.view endEditing:YES];
  628. }
  629.  
  630. -(void) registerForKeyboardNotifications
  631. {
  632. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillShowNotification object:nil];
  633. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
  634. }
  635.  
  636.  
  637. -(void) freeKeyboardNotifications
  638. {
  639. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
  640. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
  641. }
  642.  
  643.  
  644. -(void)keyboardWasShown:(NSNotification*)aNotification
  645. {
  646. NSLog(@"Keyboard was shown %ld",self.messageTextField.autocorrectionType);
  647. //NSLog(@"Content Size: %f", self.tableView.contentSize.height);
  648. if(keyboardShow == NO){
  649. NSLog(@"KEYBOARD-SHOW == NO!");
  650. //CGFloat content_h = self.tableView.contentSize.height;
  651. NSDictionary* info = [aNotification userInfo];
  652. NSTimeInterval animationDuration;
  653. UIViewAnimationCurve animationCurve;
  654. CGRect keyboardFrame;
  655. [[info objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
  656. [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
  657. [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] getValue:&keyboardFrame];
  658.  
  659. // CGFloat viewport_h_with_kb = self.view.frame.size.height - keyboardFrame.size.height;
  660. // CGFloat navbar_h = 64.0;
  661. // CGFloat textbox_h = 44.0;
  662. // CGFloat messages_viewport_h_with_kb = viewport_h_with_kb - navbar_h - textbox_h;
  663. //CGFloat viewport_final_h = viewport_h_with_kb;
  664.  
  665. /////
  666. [self.view layoutIfNeeded];
  667. [UIView animateWithDuration:animationDuration animations:^{
  668. self.layoutContraintBottomBarMessageBottomView.constant = keyboardFrame.size.height;
  669. [self.view layoutIfNeeded];
  670. }];
  671. /////
  672.  
  673. keyboardShow = YES;
  674. }
  675. else {
  676. NSLog(@"Suggestion hide/show");
  677. NSLog(@"KEYBOARD-SHOW == YES!");
  678. //START apertura e chiusura suggerimenti keyboard
  679. NSDictionary* info = [aNotification userInfo];
  680. CGRect keyboardFrame;
  681. [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] getValue:&keyboardFrame];
  682. CGFloat beginHeightKeyboard = keyboardFrame.size.height;
  683. NSLog(@"Keyboard info1 %f",beginHeightKeyboard);
  684. [[info objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrame];
  685. CGFloat endHeightKeyboard = keyboardFrame.size.height;
  686. NSLog(@"Keyboard info2 %f",endHeightKeyboard);
  687. CGFloat difference = beginHeightKeyboard-endHeightKeyboard;
  688.  
  689. NSLog(@"Difference: %f", difference);
  690. NSTimeInterval animationDuration;
  691. // CGFloat viewport_h_with_kb = self.view.frame.size.height + difference;
  692. // CGFloat viewport_final_h = viewport_h_with_kb;
  693.  
  694. [self.view layoutIfNeeded];
  695. [UIView animateWithDuration:animationDuration animations:^{
  696. self.layoutContraintBottomBarMessageBottomView.constant = keyboardFrame.size.height;
  697. [self.view layoutIfNeeded];
  698. }];
  699. /////
  700. }
  701.  
  702. }
  703.  
  704. -(void) keyboardWillHide:(NSNotification*)aNotification
  705. {
  706. NSLog(@"KEYBOARD HIDING...");
  707. NSDictionary* info = [aNotification userInfo];
  708. NSTimeInterval animationDuration;
  709. UIViewAnimationCurve animationCurve;
  710. CGRect keyboardFrame;
  711. [[info objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
  712. [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
  713. [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] getValue:&keyboardFrame];
  714.  
  715. //START ANIMATION VIEW
  716. [self.view layoutIfNeeded];
  717. [UIView animateWithDuration:animationDuration animations:^{
  718. self.layoutContraintBottomBarMessageBottomView.constant = 0;
  719. [self.view layoutIfNeeded];
  720. }];
  721. /////
  722. keyboardShow = NO;
  723. //END ANIMATION VIEW
  724.  
  725. }
  726. //---------------------------------------------------//
  727. //FINE GESTIONE KEYBOARD
  728. //---------------------------------------------------//
  729.  
  730. -(NSString*)formatDateMessage:(int)numberDaysBetweenChats message:(ChatMessage*)message row:(CGFloat)row {
  731. NSString *dateChat;
  732. if(numberDaysBetweenChats>0 || row==0){
  733. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  734. NSDate *today;
  735. today = [NSDate date];
  736. int days = (int)[SHPStringUtil daysBetweenDate:message.date andDate:today];
  737. if(days==0){
  738. dateChat = NSLocalizedString(@"today", nil);
  739. }
  740. else if(days==1){
  741. dateChat = NSLocalizedString(@"yesterday", nil);
  742. }
  743. else if(days<8){
  744. [dateFormatter setDateFormat:@"EEEE"];
  745. dateChat = [dateFormatter stringFromDate:message.date];
  746. }
  747. else{
  748. [dateFormatter setDateFormat:@"dd MMM"];
  749. dateChat = [dateFormatter stringFromDate:message.date];
  750. }
  751. }
  752. return dateChat;
  753. }
  754.  
  755. - (IBAction)sendAction:(id)sender {
  756. NSLog(@"sendAction()");
  757. NSString *text = self.messageTextField.text;
  758. [self sendMessage:text];
  759. }
  760.  
  761. -(void)sendMessage:(NSString *)text {
  762. [self sendMessage:text attributes:nil];
  763. // // check: if in a group, are you still a member?
  764. // if (self.group) {
  765. // if ([self.group isMember:self.applicationContext.loggedUser.username]) {
  766. // } else {
  767. // [self hideBottomView:YES];
  768. // [self.messageTextField resignFirstResponder];
  769. // return;
  770. // }
  771. // }
  772. //
  773. // NSString *trimmed_text = [text stringByTrimmingCharactersInSet:
  774. // [NSCharacterSet whitespaceCharacterSet]];
  775. // if(trimmed_text.length > 0) {
  776. // [self.conversationHandler sendMessageWithText:text type:MSG_TYPE_TEXT attributes:nil];
  777. // self.messageTextField.text = @"";
  778. // }
  779. }
  780.  
  781. -(void)sendMessage:(NSString *)text attributes:(NSDictionary *)attributes {
  782.  
  783. // check: if in a group, are you still a member?
  784. if (self.group) {
  785. NSString *firebase_sanitized_userid = [self.applicationContext.loggedUser.username stringByReplacingOccurrencesOfString:@"." withString:@"_"];
  786. if (![self.group isMember:firebase_sanitized_userid]) {
  787. [self hideBottomView:YES];
  788. [self.messageTextField resignFirstResponder];
  789. return;
  790. }
  791. }
  792.  
  793. NSString *trimmed_text = [text stringByTrimmingCharactersInSet:
  794. [NSCharacterSet whitespaceCharacterSet]];
  795. if(trimmed_text.length > 0) {
  796. [self.conversationHandler sendMessageWithText:text type:MSG_TYPE_TEXT attributes:attributes];
  797. self.messageTextField.text = @"";
  798. }
  799. }
  800.  
  801. -(void)sendDropboxMessage:(NSString *)name link:(NSString *)link size:(NSNumber *)size iconURL:(NSString *)iconURL thumbs:(NSDictionary *)thumbs {
  802.  
  803. // check: if in a group, are you still a member?
  804. if (self.group) {
  805. if ([self.group isMember:self.applicationContext.loggedUser.username]) {
  806. } else {
  807. [self hideBottomView:YES];
  808. [self.messageTextField resignFirstResponder];
  809. return;
  810. }
  811. }
  812.  
  813. NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];
  814. NSLog(@"dropbox.link: %@", link);
  815. NSLog(@"dropbox.size: %@", size);
  816. NSLog(@"dropbox.iconurl: %@", iconURL);
  817.  
  818. [attributes setValue:link forKey:@"link"];
  819. [attributes setValue:size forKey:@"size"];
  820. [attributes setValue:iconURL forKey:@"iconURL"];
  821. if (thumbs) {
  822. NSArray*keys=[thumbs allKeys];
  823. for (NSString *k in keys) {
  824. NSURL *turl = (NSURL *)thumbs[k];
  825. [attributes setValue:[turl absoluteString] forKey:k];
  826. }
  827. }
  828. NSString *text = [NSString stringWithFormat:@"%@ %@", name, link];
  829. [self.conversationHandler sendMessageWithText:text type:MSG_TYPE_DROPBOX attributes:attributes];
  830. }
  831.  
  832. - (IBAction)prindb:(id)sender {
  833. NSLog(@"Printing messages...");
  834. [self printDBMessages];
  835. }
  836.  
  837. -(void)printDBMessages {
  838. NSLog(@"--- all messages for conv %@", self.conversationId);
  839. NSArray *messages = [[ChatDB getSharedInstance] getAllMessagesForConversation:self.conversationId];
  840. for (ChatMessage *msg in messages) {
  841. //NSLog(@"*** MESSAGE FROM SQLITE\n****\nmessageId:%@\nconversationid:%@\nsender:%@\nrecipient:%@\ntext:%@\nstatus:%d\ntimestamp:%@", msg.messageId, msg.conversationId, msg.sender, msg.recipient, msg.text, msg.status, msg.date);
  842. NSLog(@"%@>%@:%@ [%@]", msg.sender, msg.recipient, msg.text, msg.messageId);
  843. }
  844.  
  845. // NSLog(@"--- all messages:");
  846. // NSArray *allmessages = [[ChatDB getSharedInstance] getAllMessages];
  847. // for (ChatMessage *msg in allmessages) {
  848. // //NSLog(@"*** MESSAGE FROM SQLITE\n****\nmessageId:%@\nconversationid:%@\nsender:%@\nrecipient:%@\ntext:%@\nstatus:%d\ntimestamp:%@", msg.messageId, msg.conversationId, msg.sender, msg.recipient, msg.text, msg.status, msg.date);
  849. // NSLog(@"%@>%@:%@ [id:%@ conv:%@]", msg.sender, msg.recipient, msg.text, msg.messageId, msg.conversationId);
  850. // }
  851.  
  852. }
  853.  
  854. -(void)finishedReceivingMessage:(ChatMessage *)message {
  855. NSLog(@"MessagesVC. NEW MESSAGE: %@", message.text);
  856. // for (ChatMessage *m in self.conversationHandler.messages) {
  857. // NSLog(@"text: %@", m.text);
  858. // }
  859.  
  860. // SE MESSAGGIO.TIMESTAMP < "1 SEC FA" MOSTRA SUBITO. SE MESSAGGIO >= 1 SEC FA IMPOSTA UN TIMER. SE ARRIVA UN ALTRO MESSAGGIO DURANTE IL TIMER FAI RIPARTIRE IL TIMER. AFTER THE TIMER ENDS, RELOAD TABLE.
  861.  
  862. if (!self.playingSound) {
  863. NSLog(@"playing sound for message %@ archived?: %d", message.text, message.archived);
  864. [self playSound];
  865. }
  866. [containerTVC reloadDataTableView];
  867. [containerTVC scrollToLastMessage:YES];
  868. }
  869.  
  870. -(void)playSound {
  871. double now = [[NSDate alloc] init].timeIntervalSince1970;
  872. if (now - self.lastPlayedSoundTime < 3) {
  873. NSLog(@"TOO EARLY TO PLAY ANOTHER SOUND");
  874. return;
  875. }
  876. // help: https://github.com/TUNER88/iOSSystemSoundsLibrary
  877. // help: http://developer.boxcar.io/blog/2014-10-08-notification_sounds/
  878. NSString *path = [NSString stringWithFormat:@"%@/inline.caf", [[NSBundle mainBundle] resourcePath]];
  879. NSURL *fileURL = [NSURL fileURLWithPath:path];
  880. AudioServicesCreateSystemSoundID((__bridge_retained CFURLRef)fileURL,&soundID);
  881. AudioServicesPlaySystemSound(soundID);
  882. // [self startSoundTimer];
  883.  
  884. self.lastPlayedSoundTime = now;
  885. }
  886.  
  887. //static float soundTime = 3.0;
  888. //
  889. //-(void)startSoundTimer {
  890. // self.playingSound = YES;
  891. // self.soundTimer = [NSTimer scheduledTimerWithTimeInterval:soundTime target:self selector:@selector(endSoundTimer) userInfo:nil repeats:NO];
  892. //}
  893. //
  894. //-(void)endSoundTimer {
  895. // [self.soundTimer invalidate];
  896. // self.soundTimer = nil;
  897. // self.playingSound = NO;
  898. //}
  899.  
  900. //DEPRECATO da eliminare dal protocollo
  901. -(void)reloadView {
  902. //[self.tableView reloadData];
  903. }
  904.  
  905.  
  906.  
  907. //# user images
  908. //- (void)startIconDownload:(NSString *)username forIndexPath:(NSIndexPath *)indexPath
  909. //{
  910. // NSString *imageURL = [SHPUser photoUrlByUsername:username];
  911. // SHPImageDownloader *iconDownloader = [self.imageDownloadsInProgress objectForKey:imageURL];
  912. // // NSLog(@"IconDownloader..%@", iconDownloader);
  913. // if (iconDownloader == nil)
  914. // {
  915. // iconDownloader = [[SHPImageDownloader alloc] init];
  916. // // NSMutableDictionary *options = [[NSMutableDictionary alloc] init];
  917. // // [options setObject:indexPath forKey:@"indexPath"];
  918. // // iconDownloader.options = options;
  919. // iconDownloader.imageURL = imageURL;
  920. // iconDownloader.delegate = self;
  921. // [self.imageDownloadsInProgress setObject:iconDownloader forKey:imageURL];
  922. // [iconDownloader startDownload];
  923. // }
  924. //}
  925. //
  926. //// called by our ImageDownloader when an icon is ready to be displayed
  927. //- (void)appImageDidLoad:(UIImage *)image withURL:(NSString *)imageURL downloader:(SHPImageDownloader *)downloader
  928. //{
  929. //// SHPImageDownloader *downloader = (SHPImageDownloader *) [self.imageDownloadsInProgress objectForKey:imageURL];
  930. // downloader.delegate = nil;
  931. // UIImage *circled = [SHPImageUtil circleImage:image];
  932. // [self.applicationContext.smallImagesCache addImage:circled withKey:imageURL];
  933. // [self.imageDownloadsInProgress removeObjectForKey:imageURL];
  934. // [self.tableView reloadData];
  935. //}
  936.  
  937. -(void)terminatePendingImageConnections {
  938. NSLog(@"'''''''''''''''''''''' Terminate all pending IMAGE connections...");
  939. NSArray *allDownloads = [self.imageDownloadsInProgress allValues];
  940. NSLog(@"total downloads: %d", (int)allDownloads.count);
  941. for(SHPImageDownloader *obj in allDownloads) {
  942. obj.delegate = nil;
  943. }
  944. [allDownloads makeObjectsPerformSelector:@selector(cancelDownload)];
  945. }
  946.  
  947. // end user images
  948.  
  949. -(void)disposeResources {
  950. [self terminatePendingImageConnections];
  951. }
  952.  
  953. -(void)dealloc {
  954. NSLog(@"Deallocating MessagesViewController.");
  955. }
  956.  
  957.  
  958.  
  959. //EXTRA
  960. -(void)customRoundImage:(UIView *)customImageView
  961. {
  962. customImageView.layer.cornerRadius = 15;
  963. customImageView.layer.masksToBounds = NO;
  964. customImageView.layer.borderWidth = 0;
  965. customImageView.layer.borderColor = [UIColor grayColor].CGColor;
  966. }
  967.  
  968. -(void)customcornerRadius:(UIView *)customImageView cornerRadius:(CGFloat)cornerRadius
  969. {
  970. customImageView.layer.cornerRadius = cornerRadius;
  971. customImageView.layer.masksToBounds = NO;
  972. customImageView.layer.borderWidth = 0;
  973. }
  974.  
  975. - (IBAction)menuAction:(id)sender {
  976. //[self.menuSheet showInView:self.parentViewController.tabBarController.view];
  977. }
  978.  
  979. -(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
  980. // if (actionSheet == self.menuSheet) {
  981. // NSString *option = [actionSheet buttonTitleAtIndex:buttonIndex];
  982. //
  983. // if ([option isEqualToString:@"Info gruppo"]) {
  984. // [self performSegueWithIdentifier:@"GroupInfo" sender:self];
  985. // }
  986. // else if ([option isEqualToString:@"Invia immagine"]) {
  987. // NSLog(@"invia immagine");
  988. // [self.photoMenuSheet showInView:self.parentViewController.tabBarController.view];
  989. // }
  990. // } else {
  991. // switch (buttonIndex) {
  992. // case 0:
  993. // {
  994. // [self takePhoto];
  995. // break;
  996. // }
  997. // case 1:
  998. // {
  999. // [self chooseExisting];
  1000. // break;
  1001. // }
  1002. // }
  1003. // }
  1004. }
  1005.  
  1006. // In a storyboard-based application, you will often want to do a little preparation before navigation
  1007. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  1008. if ([[segue identifier] isEqualToString:@"GroupInfo"]) {
  1009. GroupInfoVC *vc = (GroupInfoVC *)[segue destinationViewController];
  1010. NSLog(@"vc %@", vc);
  1011. vc.applicationContext = self.applicationContext;
  1012. vc.groupId = self.group.groupId;
  1013. }
  1014. }
  1015.  
  1016. // **************************************************
  1017. // **************** TAKE PHOTO SECTION **************
  1018. // **************************************************
  1019.  
  1020. - (void)takePhoto {
  1021. NSLog(@"taking photo with user %@...", self.applicationContext.loggedUser);
  1022. if (self.imagePickerController == nil) {
  1023. [self initializeCamera];
  1024. }
  1025. [self presentViewController:self.imagePickerController animated:YES completion:^{NSLog(@"FINITO!");}];
  1026. }
  1027.  
  1028. - (void)chooseExisting {
  1029. NSLog(@"choose existing...");
  1030. if (self.photoLibraryController == nil) {
  1031. [self initializePhotoLibrary];
  1032. }
  1033. [self presentViewController:self.photoLibraryController animated:YES completion:nil];
  1034. }
  1035.  
  1036. -(void)initializeCamera {
  1037. NSLog(@"cinitializeCamera...");
  1038. self.imagePickerController = [[UIImagePickerController alloc] init];
  1039. self.imagePickerController.delegate = self;
  1040. self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
  1041. // enable to crop
  1042. self.imagePickerController.allowsEditing = YES;
  1043. }
  1044.  
  1045. -(void)initializePhotoLibrary {
  1046. NSLog(@"initializePhotoLibrary...");
  1047. self.photoLibraryController = [[UIImagePickerController alloc] init];
  1048. self.photoLibraryController.delegate = self;
  1049. self.photoLibraryController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;// SavedPhotosAlbum;// SavedPhotosAlbum;
  1050. self.photoLibraryController.allowsEditing = YES;
  1051. //self.photoLibraryController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  1052. }
  1053.  
  1054. -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
  1055. [picker dismissViewControllerAnimated:YES completion:nil];
  1056. [self afterPickerCompletion:picker withInfo:info];
  1057. }
  1058.  
  1059. -(void)afterPickerCompletion:(UIImagePickerController *)picker withInfo:(NSDictionary *)info {
  1060. self.bigImage = [info objectForKey:@"UIImagePickerControllerEditedImage"];
  1061. NSLog(@"BIG IMAGE: %@", self.bigImage);
  1062. // enable to crop
  1063. // self.scaledImage = [info objectForKey:@"UIImagePickerControllerEditedImage"];
  1064. NSLog(@"edited image w:%f h:%f", self.bigImage.size.width, self.bigImage.size.height);
  1065. if (!self.bigImage) {
  1066. self.bigImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
  1067. NSLog(@"original image w:%f h:%f", self.bigImage.size.width, self.bigImage.size.height);
  1068. }
  1069. // end
  1070.  
  1071. self.scaledImage = [SHPImageUtil scaleImage:self.bigImage toSize:CGSizeMake(self.applicationContext.settings.uploadImageSize, self.applicationContext.settings.uploadImageSize)];
  1072. NSLog(@"SCALED IMAGE w:%f h:%f", self.scaledImage.size.width, self.scaledImage.size.height);
  1073.  
  1074. if (picker == self.imagePickerController) {
  1075. UIImageWriteToSavedPhotosAlbum(self.bigImage, self,
  1076. @selector(image:didFinishSavingWithError:contextInfo:), nil);
  1077. }
  1078.  
  1079. NSLog(@"image: %@", self.scaledImage);
  1080. // UIImage *imageEXIFAdjusted = [SHPImageUtil adjustEXIF:self.scaledImage];
  1081. // NSData *imageData = UIImageJPEGRepresentation(imageEXIFAdjusted, 90);
  1082.  
  1083. // PFFile *imageFile = [PFFile fileWithName:@"image.png" data:imageData];
  1084. // NSLog(@"imageFile: %@", imageFile);
  1085. //
  1086. // PFObject *userPhoto = [PFObject objectWithClassName:@"Image"];
  1087. // NSLog(@"userPhoto: %@", userPhoto);
  1088. // userPhoto[@"file"] = imageFile;
  1089. // [userPhoto saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
  1090. // if (succeeded) {
  1091. // NSLog(@"Image saved.");
  1092. // PFFile *imageFile = userPhoto[@"file"];
  1093. // [imageFile getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
  1094. // if (!error) {
  1095. // NSLog(@"Downloading image...");
  1096. // UIImage *image = [UIImage imageWithData:imageData];
  1097. // UIImageWriteToSavedPhotosAlbum(image, self,
  1098. // @selector(image:didFinishSavingWithError:contextInfo:), nil);
  1099. // }
  1100. // }];
  1101. // }
  1102. // }];
  1103. // NSLog(@"userPhoto: %@", userPhoto);
  1104. }
  1105.  
  1106. - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  1107. {
  1108. if (error != NULL) {
  1109. NSLog(@"(SHPTakePhotoViewController) Error saving image to camera roll.");
  1110. }
  1111. else {
  1112. //NSLog(@"(SHPTakePhotoViewController) Image saved to camera roll. w:%f h:%f", self.image.size.width, self.image.size.height);
  1113. }
  1114. }
  1115.  
  1116. // **************************************************
  1117. // *************** END PHOTO SECTION ****************
  1118. // **************************************************
  1119.  
  1120. @end
Add Comment
Please, Sign In to add comment