summaryrefslogtreecommitdiff
path: root/Juick/APIClient.m
blob: beace7c01865663ca56e9c4eba50fd3aea03c8b0 (plain) (blame)
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
//
//  APIClient.m
//  Juick
//
//  Created by Vitaly Takmazov on 22/08/16.
//  Copyright © 2016 com.juick. All rights reserved.
//
#import "APIClient.h"
#import "PDKeychainBindings.h"
#import "Message.h"

@implementation APIClient

+(APIClient *) sharedClient {
    static APIClient *sharedAPIClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedAPIClient = [[self alloc] init];
    });
    return sharedAPIClient;
}

-(id)init {
    if (self = [super init]) {
        self.manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"https://api.juick.com"]];
        self.manager.requestSerializer = [AFJSONRequestSerializer new];
    }
    return self;
}

-(void) pullNextFromPath:(NSString *)path  params:(NSDictionary *) params callback:(void(^)(NSArray *, NSError *))callback {
    AFHTTPSessionManager *manager = [APIClient sharedClient].manager;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [manager GET:path parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSMutableArray *messages = [NSMutableArray new];
            [((NSArray *)responseObject) enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [messages addObject:[Message yy_modelWithJSON:obj]];
            }];
            dispatch_async(dispatch_get_main_queue(), ^{
                callback(messages, nil);
            });
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"REST Error: %@", error);
            NSInteger statusCode = ((NSHTTPURLResponse *)task.response).statusCode;
            if (statusCode == 401) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    callback(nil, [[NSError alloc] initWithDomain:@"JuickErrorDomain" code:401 userInfo:nil]);
                });
            }
        }];
    });
}


+(NSString *) messagesUrl {
    return @"/messages";
}

+(NSString *) threadUrl {
    return @"/thread";
}

+(NSString *) feedUrl {
    return @"/home";
}

@end