-
Notifications
You must be signed in to change notification settings - Fork 2
/
WebData.m
executable file
·1885 lines (1511 loc) · 71.9 KB
/
WebData.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// WebData.m
// Scrape Test
//
// Created by Jeremy Gould on 11/25/13.
// Copyright (c) 2013 edu.self. All rights reserved.
//
#import "WebData.h"
#import "UIImage+Resize.h"
#import "XMLDelegateBug.h"
#import "hpple/TFHpple.h"
@implementation WebData
@synthesize managedObjectContext;
@synthesize managedObjectModel;
@synthesize persistentStoreCoordinator;
@synthesize feedbackLabel;
// Constructor with no arguments
- (id) initWithContext: (NSManagedObjectContext *) cxt{
self = [super init];
if (self){
managedObjectContext = cxt;
}
self.dateFormatter = [[NSDateFormatter alloc] init];
[self.dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssz"];
// REGEXP: A string enclosed in square braces beginning with http and then any character other than space, at least once,
// then a space and any character other than a right square brace at least once, and a trailing right square brace.
self.wikiStyleLink = [NSRegularExpression regularExpressionWithPattern:@"\\[http[^ ]+ ([^]]+)\\]"
options:NSRegularExpressionCaseInsensitive
error:nil];
self.downloadInProgress = FALSE;
return self;
}
/* ====================================================
setFeedbackLabel - pjc
====================================================
- (void) setFeedbackLabel:(UILabel *)feedbackLabelIn {
feedbackLabel = feedbackLabelIn;
}
*/
/* ====================================================
getFeedbackLabel
====================================================
- (UILabel *) getFeedbackLabel {
return feedbackLabel;
}
*/
/* ====================================================
getStreamWeb
====================================================
*/
- (Stream *) getStreamWeb:(NSString *) stream{
Stream * result;
NSString *url = [NSString stringWithFormat:@"http://wikieducator.org/index.php?title=%@&action=raw", stream];
NSURL *urlRequest = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData* data = [NSData dataWithContentsOfURL:
urlRequest];
NSString *streamString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//////NSLog(streamString);
NSMutableArray * mstr = [NSMutableArray arrayWithArray: [streamString componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"{}|"]]];
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] '='"];
[mstr filterUsingPredicate:sPredicate];
result = [[Stream alloc] init];
NSArray * prop;
NSString * label;
NSString * value;
for (NSString * object in mstr) {
prop = [object componentsSeparatedByString:@"="];
//////NSLog([prop componentsJoinedByString:@"&\n"]);
if ([prop count] > 1) {
label = [prop objectAtIndex:0];
value = [prop objectAtIndex:1];
if ([label isEqualToString:@"Stream "] && (label != nil)) {
result.title = value;
}
else if ([label isEqualToString:@"Latitude "]) {
result.latitude = value;
}
else if ([label isEqualToString:@"Longitude "]) {
result.longitude = value;
}
else if ([label isEqualToString:@"State or Province"]) {
result.stateOrProvince = value;
}
else if ([label isEqualToString:@"Country "]) {
result.country = value;
}
}
} // end iteration through mstr
//////NSLog([result toString]);
return result;
}
/* ====================================================
getBugWebOld
====================================================
*/
- (Invertebrate *) getBugWebOld:(NSString *) bug{
Invertebrate *result;
NSString *url = [NSString stringWithFormat:@"http://wikieducator.org/index.php?title=%@&action=raw", bug];
NSURL *urlRequest = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData* data = [NSData dataWithContentsOfURL:
urlRequest];
NSString *bugString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSMutableArray * mstr = [NSMutableArray arrayWithArray: [bugString componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"{}|"]]];
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] '='"];
[mstr filterUsingPredicate:sPredicate];
result = [[Invertebrate alloc] init];
NSArray * prop;
NSString * label;
NSString * value;
for (NSString * object in mstr) {
prop = [object componentsSeparatedByString:@"="];
if ([prop count] > 1) {
////////NSLog([prop objectAtIndex:0]);
////////NSLog([prop objectAtIndex:1]);
label = [prop objectAtIndex:0];
value = [prop objectAtIndex:1];
if ([label isEqualToString:@"name"]) {
////////NSLog(@"NAMED");
result.name = value;
}
else if ([label isEqualToString:@"order"]) {
////////NSLog(@"ORDERED");
result.order = value;
}
else if ([label isEqualToString:@"family"]) {
////////NSLog(@"FAMILIED");
result.family = value;
}
else if ([label isEqualToString:@"genus"]) {
////////NSLog(@"GENUSED");
result.genus = value;
}
else if ([label isEqualToString:@"image"]) {
////////NSLog(@"GENUSED");
result.imageFile = value;
}
// new additions Bijay
else if ([label isEqualToString:@"common name"]) {
result.commonName = value;
}
else if ([label isEqualToString:@"tied fly"]) {
result.flyName = value;
}
else if ([label isEqualToString:@"text"]) {
////////NSLog(@"TEXTED");
value = [value stringByReplacingOccurrencesOfString:@"[" withString:@""];
value = [value stringByReplacingOccurrencesOfString:@"]" withString:@""];
result.text = value;
// Bijay: added this to accomodate stop signs
if ([value rangeOfString:@"<!--Stop-->"].location == NSNotFound) {
result.text = value;
} else {
NSArray *arrayWithTwoStrings = [value componentsSeparatedByString:@"<!--Stop-->"];
result.text = [arrayWithTwoStrings objectAtIndex:0];
NSLog(@"%@", result.text);
}
}
}
} // end iteration through mstr
return result;
}
/* ====================================================
getBugWeb
====================================================
*/
- (Invertebrate *) getBugWeb:(NSString *) bug {
NSString *url = [NSString stringWithFormat:@"http://wikieducator.org/api.php?titles=%@&action=query&export&exportnowrap", bug];
NSURL *urlRequest = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData* data = [NSData dataWithContentsOfURL:urlRequest];
XMLDelegateBug *bugDelegate = [[XMLDelegateBug alloc] init];
//Strip starting XML to <page><text>, then send {{InsectSection to fn below
// Make sure that there is data.
if (data != nil) {
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
xmlParser.delegate = bugDelegate;
[xmlParser parse];
} else {
NSLog(@"No data returned from getBugWeb API call!!");
NSLog(@"%@",url);
}
NSArray* bugStringArray = [bugDelegate getArray];
//NSString *bugString = [objectAtIndex:0];
//for(NSString* bugString in bugStringArray)
// NSLog(@"Bug:%@",bugString);
return [self parseBug:[bugStringArray objectAtIndex:0]];
}
/* ====================================================
getBugsWeb
====================================================
*/
- (NSArray<Invertebrate *> *) getBugsWeb:(NSArray<NSString *> *) allBugs {
NSMutableArray<Invertebrate *> *invertebrateArray = [[NSMutableArray alloc] init];
//Limit number of bugs to 50 per call
NSArray<NSArray*> *bugSets = [self splitArray:allBugs :50];
for(NSArray<NSString *> *bugs in bugSets) {
//Build URL portion
NSString *bugsTextURL = [self appendStringsForURL:bugs :@"Template:" :@"|"];
NSLog(@"%@", [NSString stringWithFormat:@"Downloading Bug Data for %@", bugsTextURL]);
NSString *url = [NSString stringWithFormat:@"http://wikieducator.org/api.php?titles=%@&action=query&export&exportnowrap", bugsTextURL];
NSURL *urlRequest = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData* data = [NSData dataWithContentsOfURL:urlRequest];
XMLDelegateBug *bugDelegate = [[XMLDelegateBug alloc] init];
// Make sure that there is data.
if (data != nil) {
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
xmlParser.delegate = bugDelegate;
[xmlParser parse];
} else {
NSLog(@"No data returned from getBugWeb API call!!");
NSLog(@"%@",url);
}
NSArray* bugStringArray = [bugDelegate getArray];
for(NSString* bugString in bugStringArray) {
Invertebrate *bug = [self parseBug:bugString];
bug.imageRevDate = bugDelegate.timestamp;
[self saveBug:bug];
[invertebrateArray addObject:bug];
}
}
return invertebrateArray;
}
/*
====================================================
parseBug
====================================================
*/
- (Invertebrate *) parseBug:(NSString *) insectSection {
Invertebrate *result;
NSMutableArray * mstr = [NSMutableArray arrayWithArray: [insectSection componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"{}|"]]];
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] '='"];
[mstr filterUsingPredicate:sPredicate];
result = [[Invertebrate alloc] init];
NSArray * prop;
NSString * label;
NSString * value;
for (NSString * object in mstr) {
prop = [object componentsSeparatedByString:@"="];
if ([prop count] > 1) {
label = [[prop objectAtIndex:0] stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
value = [[prop objectAtIndex:1] stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([label isEqualToString:@"name"]) {
result.name = value;
}
else if ([label isEqualToString:@"order"]) {
result.order = value;
}
else if ([label isEqualToString:@"family"]) {
result.family = value;
}
else if ([label isEqualToString:@"genus"]) {
result.genus = value;
}
else if ([label isEqualToString:@"image"]) {
result.imageFile = value;
}
// new additions Bijay
else if ([label isEqualToString:@"common name"]) {
result.commonName = value;
}
else if ([label isEqualToString:@"tied fly"]) {
result.flyName = value;
}
else if ([label isEqualToString:@"text"]) {
result.text = value;
// Bijay: added this to accomodate stop signs
if ([value rangeOfString:@"<!--Stop-->"].location == NSNotFound) {
result.text = value;
} else {
NSArray *arrayWithTwoStrings = [value componentsSeparatedByString:@"<!--Stop-->"];
result.text = [arrayWithTwoStrings objectAtIndex:0];
//NSLog(@"%@", result.text);
}
// Put this after the check for Stop. Maybe we'll save a bit of processing time.
result.text = [self fixWikiStyleLinks:result.text];
}
}
}
return result;
}
/*
====================================================
getStreamsWeb
====================================================
*/
-(NSDictionary *) getStreamsWeb: (NSArray<NSString *> *) allStreams {
// Downloads data for stream from web using API and creates a NSDictionary of strings with all of the templates associated with streams as the value and the steam title as the key. Format is Acroneuria, Anotcha, etc., WITHOUT the preceeding "Template:"
NSMutableDictionary *streamPopulation = [[NSMutableDictionary alloc] init];
//Limit number of streams to 50 per call
NSArray<NSArray*> *streamSet = [self splitArray:allStreams :50];
for(NSArray<NSString*> *streams in streamSet) {
//Build URL portion
NSString *streamsTextURL = [self appendStringsForURL:streams :@"" :@"|"];
NSLog(@"%@", [NSString stringWithFormat:@"Downloading Stream Data for %@", streamsTextURL]);
NSString *url = [NSString stringWithFormat:@"http://wikieducator.org/api.php?titles=%@&action=query&export&exportnowrap", streamsTextURL];
NSURL *urlRequest = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData* data = [NSData dataWithContentsOfURL:urlRequest];
NSLog(@"Download Finished, Parsing");
XMLDelegateBug *streamDelegate = [[XMLDelegateBug alloc] init];
// Make sure that there is data.
if (data != nil) {
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
xmlParser.delegate = streamDelegate;
[xmlParser parse];
} else {
NSLog(@"No data returned from getStreamsWeb API call!!");
NSLog(@"%@",url);
}
NSArray *streamStringArray = [streamDelegate getArray];
for(NSString *streamString in streamStringArray) {
Stream *curStream = [self parseStreamInfo:streamString];
[self saveStream:curStream];
[streamPopulation setObject:[self parseStreamBugs:streamString] forKey:curStream.title];
}
}
return streamPopulation;
}
/* ====================================================
parseStreamInfo
====================================================
*/
- (Stream *) parseStreamInfo:(NSString *) streamString{
NSMutableArray * mstr = [NSMutableArray arrayWithArray: [streamString componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"{}|"]]];
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] '='"];
[mstr filterUsingPredicate:sPredicate];
Stream *result = [[Stream alloc] init];
NSArray * prop;
NSString * label;
NSString * value;
for (NSString *object in mstr) {
prop = [object componentsSeparatedByString:@"="];
if ([prop count] > 1) {
label = [[prop objectAtIndex:0] stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
value = [[prop objectAtIndex:1] stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (label == nil) {
NSLog(@"parseStreamInfo found null label!!!");
}
else if ([label isEqualToString:@"Stream"]) {
result.title = value;
}
else if ([label isEqualToString:@"Latitude"]) {
result.latitude = value;
}
else if ([label isEqualToString:@"Longitude"]) {
result.longitude = value;
}
else if ([label isEqualToString:@"State or Province"]) {
result.stateOrProvince = value;
}
else if ([label isEqualToString:@"Country"]) {
result.country = value;
}
}
}
return result;
}
/* ====================================================
parseStreamBugs
====================================================
*/
- (NSArray<NSString *>*) parseStreamBugs:(NSString *) streamString{
NSMutableArray * mstr = [NSMutableArray arrayWithArray: [streamString componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"{}"]]];
//Loop through all {{}} until Infobox stream
int i = 0;
while([[mstr objectAtIndex:i] rangeOfString:@"Infobox stream"].location == NSNotFound) {
i++;
}
//Skip Comment
i = i+4;
NSMutableArray<NSString *> *bugsInStream = [[NSMutableArray<NSString *> alloc] init];
while(i < [mstr count] && [[mstr objectAtIndex:i] rangeOfString:@"Category:"].location == NSNotFound) {
NSString *bugName = [[mstr objectAtIndex:i] stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//Remove Blank Lines and some streams are edited to use "=" to designate Genus
if(!([bugName isEqualToString:@""]) && [bugName rangeOfString:@"="].location == NSNotFound)
[bugsInStream addObject:bugName];
i++;
}
return bugsInStream;
}
- (BOOL) bugRequiresUpdate: (InvertebrateData *)bug {
NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"InvertebrateData" inManagedObjectContext:managedObjectContext]];
[request setPredicate:[NSPredicate predicateWithFormat:@"name = %@", bug.name]];
[request setFetchLimit:1];
NSError* error = nil;
NSArray* results = [self.managedObjectContext executeFetchRequest:request error:&error];
NSLog(@"Results has: %tu", (unsigned long)[results count]);
Invertebrate* stored_bug = [results objectAtIndex:0];
NSLog(@"RESULT[0]: %@", stored_bug);
if(stored_bug == nil) {
NSLog(@"Stored bug is nil");
return YES;
} else if(error != nil) {
NSLog(@"Error is not nil");
return YES;
} else if([stored_bug.imageRevDate compare:bug.imageRevDate] == NSOrderedDescending) {
NSLog(@"Date comparison");
return YES;
} else {
NSLog(@"Default to NO");
return NO;
}
NSLog(@"Outside of the ifs");
return YES;
}
/* ====================================================
linkBugstoStreams
====================================================
*/
- (BOOL) linkBugsToStreams:(NSArray<Invertebrate *> *) bugs :(NSDictionary *) streams{
BOOL success = true;
// Check and conditionally add initial object to database
NSManagedObjectContext *context = [self managedObjectContext];
if(context == nil){
NSLog(@"Failed to get context in linkBugsToStream");
success = false;
} else {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"StreamData" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error;
for(NSString *streamName in [streams allKeys]){
StreamData *stream = [self getStreamData:streamName];
NSLog(@"Linking Bugs in Stream: %@",stream.title);
if(stream == nil) {
NSLog(@"Stream Not Found: %@", streamName);
} else {
for(NSString *bugName in [streams objectForKey:streamName]){
NSLog(@"Linking Bug %@ to Stream %@", bugName, streamName);
InvertebrateData *inv = [self getBugData:bugName];
if(inv == nil) {
NSLog(@"Bug Not Found: %@ in Stream: %@", bugName, streamName);
} else {
[stream addContainsObject:inv];
[inv addLivesInObject:stream];
}
if (![context save:&error]) {
NSLog(@"Error Saving Linkage Data for Stream: %@", streamName);
NSLog(@"%@", [error localizedDescription]);
success = false;
}
}
}
}
}
return success;
}
/*
====================================================
saveStream
====================================================
*/
- (BOOL) saveStream:(Stream *) stream {
BOOL success = true;
// Check and conditionally add initial object to database
NSManagedObjectContext *context = [self managedObjectContext];
if(context == nil) {
NSLog(@"Get Context failed in saveStream");
success = false;
} else {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"StreamData" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error;
StreamData * streamData;
streamData = [NSEntityDescription insertNewObjectForEntityForName:@"StreamData" inManagedObjectContext:context];
streamData.title = stream.title;
streamData.country = stream.country;
streamData.stateOrProvince = stream.stateOrProvince;
streamData.latitude = stream.latitude;
streamData.longitude = stream.longitude;
if (![context save:&error]) {
NSLog(@"Error Saving Data for Stream: %@", stream.title);
NSLog(@"%@", [error localizedDescription]);
success = false;
}
}
return success;
}
/*
====================================================
saveBug
====================================================
*/
- (BOOL) saveBug:(Invertebrate *) bug {
BOOL success = true;
// Check and conditionally add initial object to database
NSManagedObjectContext *context = [self managedObjectContext];
if(context == nil) {
NSLog(@"Get Context failed in saveBug");
success = false;
} else {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"InvertebrateData" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error;
InvertebrateData *bugData;
bugData = [NSEntityDescription insertNewObjectForEntityForName:@"InvertebrateData" inManagedObjectContext:context];
bugData.name = bug.name;
bugData.genus = bug.genus;
bugData.family = bug.family;
bugData.order = bug.order;
bugData.text = bug.text;
bugData.imageFile = bug.imageFile;
bugData.commonName = bug.commonName;
bugData.flyName = bug.flyName;
bugData.imageRevDate = bug.imageRevDate;
NSLog(@"%@", bugData);
if (![context save:&error]) {
NSLog(@"Error Saving Data for Bug: %@", bug.name);
NSLog(@"%@", [error localizedDescription]);
success = false;
}
}
return success;
}
/* ====================================================
getAllBugsWeb
====================================================
*/
- (NSArray *) getAllBugsWeb {
NSArray * results;
NSMutableArray * intermediateResults = [[NSMutableArray alloc] init];
NSString *url = @"http://wikieducator.org/api.php?action=query&list=categorymembers&cmtitle=Category:Aquatic%20Invertebrate&cmlimit=500&format=json&cmprop=ids%7Ctitle";
NSURL *urlRequest = [NSURL URLWithString:url];
NSError *err = nil;
NSData* data = [NSData dataWithContentsOfURL:
urlRequest];
//pjc - Fail gracefully
if(data == nil)
return nil;
NSDictionary *bugs = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&err];
if(err)
{
//Handle
}
// Intemediate steps to get inside nested dictionary
NSDictionary * bugs1 = [bugs objectForKey:(@"query")];
NSArray * bugs2 = [bugs1 objectForKey:(@"categorymembers")];
NSDictionary *currentBug;
NSString * currentName;
Invertebrate * currentInvertebrate;
for (int i = 0; i < [bugs2 count]; i++) {
currentBug = [bugs2 objectAtIndex:i];
//////NSLog([currentBug description]);
currentName = [currentBug objectForKey:@"title"];
//////NSLog(currentName);
if (currentName != nil){
currentInvertebrate = [self getBugWeb:currentName];
if (currentInvertebrate != nil){
[intermediateResults addObject:currentInvertebrate];
}
}
}
results = [NSArray arrayWithArray:intermediateResults];
return results;
}
/* ====================================================
getAllStreamsWeb
====================================================
*/
- (NSArray *) getAllStreamsWeb{
NSArray * results;
NSMutableArray * intermediateResults = [[NSMutableArray alloc] init];
NSLog(@"Downloading Stream Names");
NSString *url = @"http://wikieducator.org/api.php?action=query&list=categorymembers&cmtitle=Category:Stream&cmlimit=500&format=json&cmprop=ids%7Ctitle";
NSURL *urlRequest = [NSURL URLWithString:url];
NSError *err = nil;
NSData* data = [NSData dataWithContentsOfURL:
urlRequest];
//pjc - Fail gracefully
if(data == nil)
return nil;
NSDictionary *streams = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&err];
if(err)
{
//Handle
}
// Intemediate steps to get inside nested dictionary
NSDictionary * streams1 = [streams objectForKey:(@"query")];
NSArray * streams2 = [streams1 objectForKey:(@"categorymembers")];
NSDictionary *currentStreamDictionary;
NSString * currentName;
// TODO point 1
Stream * currentStream;
for (int i = 0; i < [streams2 count]; i++) {
currentStreamDictionary = [streams2 objectAtIndex:i];
//////NSLog([currentBug description]);
currentName = [currentStreamDictionary objectForKey:@"title"];
//////NSLog(currentName);
if (currentName != nil){
currentStream = [self getStreamWeb:currentName];
if (currentStream != nil){
[intermediateResults addObject:currentStream];
}
}
}
results = [NSArray arrayWithArray:intermediateResults];
return results;
}
//*****************************************************************************
//*****************************************************************************
// CORE DATA STUFF
//*****************************************************************************
//*****************************************************************************
/*
====================================================
synchBugs
====================================================
*/
- (void) synchBugs
{
//[aiv startAnimating];
//label.text = @"Connecting to Server...";
// Check and conditionally add initial object to database
NSManagedObjectContext *context = [self managedObjectContext];
// pull object context
if (context != nil){
[self clearBugs];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; //2
NSEntityDescription *entity = [NSEntityDescription entityForName:@"InvertebrateData" inManagedObjectContext:context]; //3
[fetchRequest setEntity:entity]; //4
NSError *error;
NSArray *bugs = [self getAllBugsWeb];
//pjc - Fail gracefully
if(bugs == nil)
return;
InvertebrateData *bug;
int i=0;
for (Invertebrate *thisBug in bugs) {
if ((thisBug.name != NULL) && ! [self myIsNil:thisBug.name]){
bug = [NSEntityDescription
insertNewObjectForEntityForName:@"InvertebrateData"
inManagedObjectContext:context];
bug.name = [self myStripper:thisBug.name];
//label.text = [NSString stringWithFormat:@"Reading %@ files...",bug.name];
bug.genus = thisBug.genus;
bug.family = thisBug.family;
bug.order = thisBug.order;
bug.text = thisBug.text;
bug.imageFile = thisBug.imageFile;
// new additions bijay
bug.commonName = thisBug.commonName;
bug.flyName = thisBug.flyName;
//pjc added release pool
@autoreleasepool {
////NSLog(thisBug.imageFile);
// Download bug image
i++;
//[feedbackLabel setText:[NSString stringWithFormat:@"Downloading Image %d of %d",i,bugs.count]];
UIImage *img = [self getImageWeb:[thisBug.imageFile stringByReplacingOccurrencesOfString:@" " withString:@"_"]];
//NSLog([img description]);
if (img!= nil){
NSString *s = [thisBug.imageFile stringByReplacingOccurrencesOfString:@"File:" withString:@""];
NSArray * se = [s componentsSeparatedByString:@"."];
if ([se count] > 1){
//pjc - debug image size, and duplicates - fix - make this a second thread
NSLog(@"Saving %@ -- size: %0.0f, %0.0f -- %d of %d", s, [img size].height, [img size].width, i, (int)bugs.count);
[self saveImage:img withFileName:[se objectAtIndex:0] ofType:[se objectAtIndex:1]];
}
}
} // end autoreleasepool
}// end of outer if
}// end of for loop
if (![context save:&error]) {
NSLog(@"Error Saving Invertebrate Data: %@", [error localizedDescription]);
}
}
}
/*
====================================================
synchStreams
====================================================
*/
- (BOOL) synchStreams
{
// Check and conditionally add initial object to database
NSManagedObjectContext *context = [self managedObjectContext];
if (context != nil){
[self clearStreams];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"StreamData" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error;
// TODO point 2
NSArray *streams = [self getAllStreamsWeb];
//pjc - Fail gracefully
if(streams == nil)
return false;
StreamData * stream;
NSArray * inhabitants;
for (Stream * thisStream in streams) {
if ((thisStream.title != NULL) && ! [self myIsNil:thisStream.title] &&
! [thisStream.title isEqualToString:@" "]){
stream = [NSEntityDescription
insertNewObjectForEntityForName:@"StreamData"
inManagedObjectContext:context];
//////NSLog(thisStream.title);
stream.title = [self myStripper:thisStream.title];
//label.text = [NSString stringWithFormat:@"Reading %@ files...",stream.title];
stream.country = [self myStripper:thisStream.country];
//NSLog(thisStream.stateOrProvince);
stream.stateOrProvince = [self myStripper:thisStream.stateOrProvince];
stream.latitude = [self myStripper:thisStream.latitude];
stream.longitude = [self myStripper:thisStream.longitude];
//NSLog(stream.stateOrProvince);
//inhabitants = [NSSet setWithArray:[self getPopulationWeb:thisStream.title]];;
//Download inhabitants for each stream
inhabitants = [self getPopulationWeb:thisStream.title];
//NSMutableArray * result = [[NSMutableArray alloc] init];
InvertebrateData * inv;
for (NSString * n in inhabitants){
inv = [self getBugData:n];
if (inv != nil){
//[result addObject:(Invertebrate*)inv];
[stream addContainsObject:inv];
} else {
NSLog(@"No data found for inhabitant %@ in stream %@!", [n description], stream.title);
}
}
//pjc - Debug stream inhabitants
//NSLog(@"%@", [thisStream.title description]);
//NSLog(@"%@", [inhabitants description]);
/*
if(inhabitants.count==0)
NSLog(@"%@ has no inhabitants!", [thisStream.title description]);
*/
//NSLog([result description]);
//stream.contains = [NSSet setWithArray:result];
}
}
if (![context save:&error]) {
NSLog(@"Error Saving Stream Data: %@", [error localizedDescription]);
}
}
//label.text = @"Synch Complete.";
//[aiv stopAnimating];
return true;
}
/*
====================================================
getAllBugs
====================================================
*/
- (NSArray *) getAllBugs{
NSManagedObjectContext *context = self.managedObjectContext;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"InvertebrateData" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *allBugs = [context executeFetchRequest:fetchRequest error:&error];
return allBugs;
}
/*
====================================================
getAllStreams
====================================================
*/
- (NSArray *) getAllStreams{
NSManagedObjectContext *context = self.managedObjectContext;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"StreamData" inManagedObjectContext:context];
//fetchRequest.returnsDistinctResults = YES;
[fetchRequest setEntity:entity];
NSError *error;
NSArray *allStreams = [context executeFetchRequest:fetchRequest error:&error];
//pjc - Fix - Alphabetize Array
/*
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES comparator:^NSComparisonResult(StreamData obj1, StreamData obj2) {
return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch];
}];
*/
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES];
return [allStreams sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
//return allStreams;
}
/*
====================================================
getAllStreamsByLocation
====================================================
*/
- (NSArray *) getAllStreamsByLocation: (NSString *) location{
NSManagedObjectContext *context = self.managedObjectContext;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"StreamData" inManagedObjectContext:context];
//NSString *str = [NSString stringWithFormat:@"(country == '%@') OR (stateOrProvince == '%@')", location, location];
NSString *str = [NSString stringWithFormat:@"stateOrProvince == '%@'", location];
// NSLog(str);
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:str]];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *allStreams = [context executeFetchRequest:fetchRequest error:&error];
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES];
return [allStreams sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
//NSLog([allStreams description]);
//return allStreams;