-
Notifications
You must be signed in to change notification settings - Fork 4
/
ORGiphyNetworkModel.m
88 lines (64 loc) · 2.5 KB
/
ORGiphyNetworkModel.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
//
// ORGiphyNetworkModel.m
// Pods
//
// Created by Orta on 8/30/14.
//
//
#import "ORGiphyNetworkModel.h"
#import <AFNetworking/AFNetworking.h>
#import "GIF.h"
@interface ORGiphyNetworkModel()
@property (nonatomic, copy, readonly) NSString *query;
@property (nonatomic, copy, readonly) NSArray *gifs;
@property (nonatomic, assign, readonly) NSInteger page;
@property (nonatomic, assign, readonly) BOOL downloading;
@property (nonatomic, assign, readonly) BOOL completed;
@end
@implementation ORGiphyNetworkModel
- (void)setQuery:(NSString *)query
{
_query = [query stringByReplacingOccurrencesOfString:@" " withString:@"+"];
_gifs = @[];
_page = 0;
_downloading = NO;
_completed = NO;
}
static NSInteger GiphyDownloadCount = 15;
- (void)getNextGIFs:(void (^)(NSArray *newGIFs, NSError *error))completion
{
if (_downloading) return;
NSParameterAssert(self.query);
NSString *address = [NSString stringWithFormat:@"http://api.giphy.com/v1/gifs/search?q=%@&offset=%@&limit=%@&api_key=%@", self.query, @(self.page), @(GiphyDownloadCount), self.APIKey];
if (!self || !address || self.completed) return;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:address parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) {
NSArray *gifs = JSON[@"data"];
NSMutableArray *mutableGIFs = [NSMutableArray array];
for (NSDictionary *dictionary in gifs) {
GIF *gif = [[GIF alloc] initWithDownloadURL:dictionary[@"images"][@"original"][@"url"]
thumbnail:dictionary[@"images"][@"downsized_still"][@"url"]
source:dictionary[@"url"]
sourceTitle:@"Giphy"];
if (gif) { [mutableGIFs addObject:gif]; }
}
_gifs = [self.gifs arrayByAddingObjectsFromArray:mutableGIFs];
_downloading = NO;
_completed = mutableGIFs.count > GiphyDownloadCount;
_page += GiphyDownloadCount;
if (completion) completion(mutableGIFs, nil);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
if (completion) completion(nil, error);
}];
_downloading = YES;
}
- (NSInteger)numberOfGifs
{
return self.gifs.count;
}
- (GIF *)gifAtIndex:(NSInteger)index
{
return self.gifs[index];
}
@end