Developer Area

root/apps/iphone/superbook/trunk/Classes/LocateThem_ViewController.m @ 461

Revision 461, 16.7 kB (checked in by henri, 5 years ago)

Changed to use NSLocalizedString and rewrote the strings localization file

Line 
1//
2//  LocateThem_AppDelegate.m
3//  LocateThem
4//
5//  Created by Henri Asseily on 8/13/08.
6/*
7 Copyright (c) 2008-2009, Telnic Ltd. All rights reserved.
8 
9 Redistribution and use in source and binary forms, with or without modification,
10 are permitted provided that the following conditions are met:
11 
12 Redistributions of source code must retain the above copyright notice, this list of conditions
13 and the following disclaimer. Redistributions in binary form must reproduce the above copyright
14 notice, this list of conditions and the following disclaimer in the documentation and/or other
15 materials provided with the distribution.
16 Neither the name of the Telnic Ltd. nor the names of its contributors may be used to endorse or
17 promote products derived from this software without specific prior written permission.
18 THIS DOCUMENTATION IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
19 OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
20 AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
21 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
24 IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27//
28
29#import "LocateThem_ViewController.h"
30
31@implementation LocateThem_ViewController
32
33@synthesize friendsTableView;
34@synthesize loadingView;
35@synthesize labelForLoadingView;
36@synthesize telSearch;
37@synthesize progressView;
38@synthesize progressLabel;
39@synthesize logo;
40
41- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
42    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
43        // Custom initialization
44                [MyCLController sharedInstance].delegate = self;
45    }
46        isFirstRun = YES;
47        shouldUpdateLocation = YES;
48    return self;
49}
50
51- (void)viewDidLoad {
52        [super viewDidLoad];
53        if (!self.title) {
54                self.title = NSLocalizedString(@"Contacts", @"Main Contacts list Title");
55               
56                // NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];   
57                FriendsData *sharedFriendsInstance = [FriendsData sharedInstance];
58                sharedFriendsInstance.delegate = self;
59                friendsTableView.dataSource = sharedFriendsInstance;
60               
61                // Do the other setup tasks
62                [telSearch setKeyboardType:UIKeyboardTypeASCIICapable];
63                [telSearch setAutocorrectionType:UITextAutocorrectionTypeNo];
64                telSearch.placeholder = NSLocalizedString(@"SearchboxPlaceholder", @"Placeholder string in .tel search box");
65                keyboardShown = NO;
66                [[NSNotificationCenter defaultCenter] addObserver:self
67                                                                                                 selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil ];
68                [[NSNotificationCenter defaultCenter] addObserver:self
69                                                                                                 selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil ];
70                [[NSNotificationCenter defaultCenter] addObserver:self
71                                                                                                 selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil ];
72                isUpdatingLocation = FALSE;
73                needsFriendsTableRefresh = TRUE;
74        }
75}
76
77- (void)viewWillAppear:(BOOL)animated {
78        [super viewWillAppear:animated];
79        // become the delegate of MyCLController, which could have been taken by a .tel tableview
80        [MyCLController sharedInstance].delegate = self;
81}
82
83- (void)viewDidAppear:(BOOL)animated {
84        [super viewDidAppear:animated];
85        // Must animate the hiding of the navbar and put it in this method
86        // otherwise the frame of the view is reduced and pushed up by the size of the navbar
87        [self.navigationController setNavigationBarHidden:YES animated:YES];
88        if (! isUpdatingLocation) {
89                [[MyCLController sharedInstance].locationManager startUpdatingLocation];
90                isUpdatingLocation = TRUE;
91        }
92
93        if (needsFriendsTableRefresh) {
94                // Now load our friends using a timer, so that the application can finish initializing
95                // and it can display the "loading..." information. Once the friend data has been loaded,
96                // friendsDataDidLoad() is called and we complete building the table.
97                // Don't use a background thread because the AddressBook framework may not be threadsafe
98                [self.labelForLoadingView setText:NSLocalizedString(@"Loading AddressBook...", @"Loading AddressBook...")];
99                [self.view addSubview:loadingView];
100                loadingView.center = self.view.center;
101                [[FriendsData sharedInstance] refreshPreferences];
102                [[FriendsData sharedInstance] performSelector:@selector(loadFriendsDataFromAB:) withObject:nil afterDelay:0.1];
103                needsFriendsTableRefresh = FALSE;
104        }
105}
106
107// Delegate for FriendsData that gets called when data has been loaded and we can update the tableview
108- (void)friendsDataDidLoad {
109
110        //[NSThread sleepForTimeInterval:5];    // for testing loadingView only
111        [friendsTableView reloadData];
112        [loadingView removeFromSuperview];
113        if ([friendsTableView numberOfRowsInSection:0] == 0) {
114                [friendsTableView setHidden:NO];
115                instructionsView = [[[UILabel alloc] initWithFrame:friendsTableView.frame] autorelease];
116                instructionsView.numberOfLines = 0;
117                instructionsView.text = NSLocalizedString(@"NoContactsWithTel", @"Paragraph to explain that no contacts could be found with a .tel url");
118                instructionsView.textAlignment = UITextAlignmentCenter;
119                instructionsView.font = [instructionsView.font fontWithSize:18];
120                instructionsView.alpha = 0.8;
121                [self.view insertSubview:instructionsView aboveSubview:friendsTableView];
122                [instructionsView resignFirstResponder];
123        } else {
124                [friendsTableView setHidden:NO];
125                if (instructionsView != nil) {
126                        [instructionsView removeFromSuperview];
127                }
128        }
129
130        if (isFirstRun) {
131                isFirstRun = NO;
132                // Check to see if the user has disabled location services altogether
133                // In that case, we show an alert and disable the find button and gps switch
134                // TODO: re-enable when find location button is brought back
135//              if ( ! [MyCLController sharedInstance].locationManager.locationServicesEnabled ) {
136//                      BOOL shouldQuit = NO;
137//                     
138//                      CustomAlertView *alertView = [[CustomAlertView alloc] initWithTitle:NSLocalizedString(@"LocationDenied", nil)
139//                                                                                                                              message:nil
140//                                                                                                                         delegate:nil
141//                                                                                                                       shouldQuit:shouldQuit
142//                                                                                                        cancelButtonTitle:nil
143//                                                                                                        otherButtonTitles:NSLocalizedString(@"OK", nil), nil];
144//                      [alertView show];
145//                      [alertView release];
146//              }
147
148
149                //register whenever a change to the underlying dataset happens, so we can update the friends list view
150                [[FriendsData sharedInstance] addObserver:self forKeyPath:@"lastFriendsUpdate"
151                                                                                  options:NSKeyValueObservingOptionNew context:NULL];
152        }
153        if (shouldUpdateLocation) {
154                shouldUpdateLocation = FALSE;
155                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
156                if ([defaults boolForKey:@"startupLocatePreference"]) {
157                        progressLabel.text = NSLocalizedString(@"Searching contact locations", @"Searching contact locations");
158                        logo.hidden = YES;
159                        progressLabel.hidden = NO;
160                        progressView.hidden = NO;                       
161                        [self performSelectorInBackground:@selector(updateFriendsListInBackground) withObject:nil];
162                }
163        }
164}
165
166- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
167        // Return YES for supported orientations
168
169        return (interfaceOrientation == UIInterfaceOrientationPortrait);
170}
171
172- (void)didReceiveMemoryWarning {
173    [super didReceiveMemoryWarning]; // Don't release the view
174}
175
176- (void)dealloc {
177        [mapViewController release];
178        [locationRefreshButton release];
179        [locationRefreshingButton release];
180        [super dealloc];
181}
182
183#pragma mark ---- Main Friend Update methods ----
184- (void)updateFriendsListInBackground {
185        // This method is to be called as a new thread and updates the friends list in the background
186        // As it updates, it will request the table view and maybe a status indicator to update in the main thread
187        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
188        mapViewController = [FriendsMapViewController sharedInstance];
189        [[MyCLController sharedInstance] findFriendsTel];
190        [pool release];
191}
192
193- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
194
195    if ([keyPath isEqual:@"lastFriendsUpdate"]) {
196                // Make sure we're in the main thread to update the UI
197                [self performSelectorOnMainThread:@selector(updateFriendsTableViewWithTimestamp:)
198                                                           withObject:[change objectForKey:NSKeyValueChangeNewKey] waitUntilDone:YES];
199                [mapViewController setMarkers:[FriendsData sharedInstance].peopleCurrentList];
200                mapViewController.navigationItem.rightBarButtonItem = locationRefreshButton;
201        }
202        else {
203                [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
204        }
205}
206
207- (void)updateFriendsTableViewWithTimestamp:(NSDate *)theStamp {
208        [[FriendsData sharedInstance] updateDataSet];   
209        [friendsTableView reloadData];
210}
211
212#pragma mark ---- Row and Accessory Click ----
213
214- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
215       
216        // Do the same as if the row is selected
217        [self tableView:tableView didSelectRowAtIndexPath:indexPath];
218
219        return;
220}
221
222- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
223       
224        mapViewController.zoomLevel = 14.0;
225        NSNumber *personId = [[FriendsData sharedInstance] getABRecordIdForIndexPath:indexPath];
226        [tableView deselectRowAtIndexPath:indexPath animated:YES];
227        [self launchNavControllerForTel:nil personId:personId];
228        return;
229}
230
231#pragma mark ---- Action methods ----
232
233- (void)launchNavControllerForTel:(NSString *)aTel personId:(NSNumber *)aPersonId {
234        NaptrViewController *nVC = [[[NaptrViewController alloc] initWithNibName:@"TelView" bundle:[NSBundle mainBundle]] autorelease];
235        if (aPersonId) {
236                if (![nVC setupWithPersonId:aPersonId])
237                        return;
238        } else if (aTel) {
239                if (![nVC setupWithTel:aTel])
240                        return;
241        } else {
242                return;
243        }
244        [self.navigationController pushViewController:nVC animated:YES];
245}       
246
247#pragma mark ---- UISearchBar delegate and keyboard methods ----
248
249- (void)keyboardWillShow:(NSNotification*)aNotification {
250        if (keyboardShown)
251                return;
252       
253        NSDictionary* info = [aNotification userInfo];
254    // Get the size of the keyboard.
255    NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
256    CGSize keyboardSize = [aValue CGRectValue].size;
257        // Move the search box up above the keyboard
258        CGRect tSFrame = telSearch.frame;
259        CGRect aboveKeyboard = CGRectMake(tSFrame.origin.x, tSFrame.origin.y - keyboardSize.height,
260                                                                          tSFrame.size.width, tSFrame.size.height);
261        telSearch.barStyle = UIBarStyleBlackOpaque;
262        self.friendsTableView.hidden = YES;
263        [UIView beginAnimations:nil context:NULL];
264        [UIView setAnimationBeginsFromCurrentState:YES];
265        [UIView setAnimationDuration:0.3];      // TODO: Change this to UIKeyboardAnimationDurationUserInfoKey for 3.x
266        telSearch.frame = aboveKeyboard;
267        [UIView commitAnimations];
268        keyboardShown = YES;
269}
270
271- (void)keyboardDidShow:(NSNotification*)aNotification {
272        // If we show the cancel button in the WillShow notification, it is disabled (2.x at least)
273        telSearch.showsCancelButton = YES;
274}
275
276- (void)keyboardWillHide:(NSNotification*)aNotification {
277        if (!keyboardShown)
278                return;
279       
280        NSDictionary* info = [aNotification userInfo];
281    // Get the size of the keyboard.
282    NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
283    CGSize keyboardSize = [aValue CGRectValue].size;
284        // Move the search box back down
285        CGRect tSFrame = telSearch.frame;
286        CGRect noKeyboard = CGRectMake(tSFrame.origin.x, tSFrame.origin.y + keyboardSize.height,
287                                                                          tSFrame.size.width, tSFrame.size.height);
288        telSearch.frame = noKeyboard;
289        telSearch.barStyle = UIBarStyleBlackTranslucent;
290        telSearch.text = @"";
291        telSearch.showsCancelButton = NO;
292        self.friendsTableView.hidden = NO;
293        keyboardShown = NO;
294}
295
296- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
297}
298
299- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
300    [searchBar resignFirstResponder];
301}
302
303- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
304        //Must grab the text before resigning first responder
305        NSString *query = [NSString stringWithString:searchBar.text];
306    [searchBar resignFirstResponder];
307        [self launchNavControllerForTel:query personId:nil];
308}
309
310#pragma mark ---- MyCLController delegate methods ----
311
312-(void)gpsUpdate:(CLLocation *)aLoc {
313//      Enable this to display the GPS update info on this controller's view
314//      if (!aLoc) {
315//              [self.labelGpsLastUpdateDate setText:NSLocalizedString(@"LatLongUnavailable", @"Latitude/Longitude unavailable")];
316//              [self.labelGpsLastUpdateDate setNeedsDisplay];
317//              return;
318//      }
319//      NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
320//      [dateFormatter setDateStyle:NSDateFormatterShortStyle];
321//      [dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
322//      [self.labelGpsLastUpdateDate setText:[dateFormatter stringFromDate:aLoc.timestamp]];
323//      [self.labelGpsLastUpdateDate setNeedsDisplay];
324//      [dateFormatter release];
325        if (!mapViewController.view.superview) {
326                // the map view is not active, we can update my location there
327                // Let's not do it for now, it's debatable from a usability perspective
328                mapViewController.initialLoc = aLoc;
329        }
330        return;
331}
332
333-(void)statusUpdate:(NSString *)update {       
334        return;
335}
336
337- (void)updateProgressView:(NSNumber *)val {
338
339        // technique to ensure we're updating the UI in the main thread, otherwise it doesn't work
340        if (![NSThread isMainThread]) {
341                return([self performSelectorOnMainThread:_cmd withObject:val waitUntilDone:YES]);
342        }
343        progressView.progress = [val floatValue];
344        if ([val floatValue] == 1.0f) {
345                progressView.hidden = YES;
346                progressLabel.hidden = YES;
347                logo.hidden = NO;
348        }
349}
350
351-(void)newError:(NSString *)text shouldQuit:(BOOL)shouldQuit {
352
353        NSString *alertMessage;
354        if (shouldQuit) {
355                alertMessage = [NSString stringWithString:NSLocalizedString(@"AppWillQuit", @"Superbook will now quit")];
356        } else {
357                alertMessage = nil;
358        }
359       
360        CustomAlertView *alertView = [[CustomAlertView alloc] initWithTitle:text
361                                                                                                                                message:alertMessage
362                                                                                                                           delegate:nil
363                                                                                                                         shouldQuit:shouldQuit
364                                                                                                          cancelButtonTitle:nil
365                                                                                                          otherButtonTitles:NSLocalizedString(@"Quit", @"Quit"), nil];
366        [alertView show];
367        [alertView release];
368        if (alertMessage)
369                [alertMessage release];
370}       
371
372#pragma mark ------ Buttons
373
374- (IBAction)didPressMapButton:(id)sender {
375        // Load up the shared map view
376        // Make the map view do a background update of the friends and display them
377        mapViewController = [FriendsMapViewController sharedInstance];
378        // Put in a dummy map navcontroller so it looks the same as when we navigate .tel domains
379        mapViewController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
380                                                                                                                                                                                 target:self
381                                                                                                                                                                                 action:@selector(closeMapNavController)];
382        // Create the buttons to refresh the markers
383        if (!locationRefreshButton) {
384                UIImage *pinrefresh = [UIImage imageNamed:@"button-pin-refresh.png"];
385                locationRefreshButton = [[UIBarButtonItem alloc] initWithImage:pinrefresh style:UIBarButtonItemStyleBordered
386                                                                                                                                target:self
387                                                                                                                                action:@selector(didPressLocationRefreshButton:)];
388        }
389        if (!locationRefreshingButton) {
390                UIActivityIndicatorView *aIV = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite] autorelease];
391                [aIV startAnimating];
392                locationRefreshingButton = [[UIBarButtonItem alloc] initWithCustomView:aIV];
393        }
394        mapViewController.navigationItem.rightBarButtonItem = locationRefreshButton;
395       
396        // Do data setup
397        [mapViewController didPressCenterGps:nil];
398        mapViewController.zoomLevel = 6.0;
399        [self.navigationController pushViewController:mapViewController animated:YES];
400}
401
402- (IBAction)didPressSettingsButton:(id)sender {
403        SettingsViewController *sVC = [[[SettingsViewController alloc] initWithNibName:@"SettingsView" bundle:[NSBundle mainBundle]] autorelease];
404        sVC.delegate = self;
405        sVC.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave
406                                                                                                                                                                                 target:sVC
407                                                                                                                                                                                 action:@selector(didPressSave:)];
408        sVC.navigationItem.backBarButtonItem.title = NSLocalizedString(@"Cancel", @"Cancel");
409        [self.navigationController pushViewController:sVC animated:YES];
410}
411
412- (IBAction)didPressLocationRefreshButton:(id)sender {
413        mapViewController.navigationItem.rightBarButtonItem = locationRefreshingButton;
414        [self performSelectorInBackground:@selector(updateFriendsListInBackground) withObject:nil];
415}
416
417#pragma mark ------ SettingsViewDelegate
418- (void)settingsDidChange {
419        needsFriendsTableRefresh = TRUE;
420        shouldUpdateLocation = TRUE;
421}
422
423- (void)launchTelUrl:(NSString *)url {
424        [self launchNavControllerForTel:url personId:nil];
425}
426
427@end
Note: See TracBrowser for help on using the browser.
Telnic
Search This Site
Partners
Neustar
ICANN
Main site | WHOIS | Sell .tel | FAQ | Archived Site | About Telnic | Contact Us