Project

General

Profile

InitializeSubscriber Objective-C » History » Version 1

Tomek Dziemidowicz, 2019-07-04 09:00 PM

1 1 Tomek Dziemidowicz
h1. InitializeSubscriber Objective-C
2
3
<pre><code class="objc">
4
-(void)initializeSubscriber:(nonnull NSString*)subscriberId error:(NSError * _Nullable * _Nullable)error{
5
    NSString *requestUrlString = [NSString stringWithFormat:@"%@/InitializeSubscriber/%@", _serverURL, subscriberId];
6
    NSURL *requestURL = [NSURL URLWithString:requestUrlString];
7
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
8
9
    [request setURL:requestURL];
10
    [request setHTTPMethod:@"GET"];
11
12
    NSHTTPURLResponse *response;
13
14
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:error];
15
16
    if(!*error){
17
        switch (response.statusCode) {
18
            case 200:
19
                break;
20
            default:
21
                *error = [NSError errorWithDomain:@"com.sqlite-sync" code:0 userInfo:[NSDictionary dictionaryWithObject:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] forKey:NSLocalizedDescriptionKey]];
22
                break;
23
        }
24
    }
25
26
    if(*error) return;
27
28
    NSDictionary* schema = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:error];
29
30
    if(*error) return;
31
32
    NSArray *keys = [[schema allKeys] sortedArrayUsingComparator:^NSComparisonResult(id a, id b) { return [a compare:b]; }];
33
34
    sqlite3 *db;
35
    sqlite3_stmt *stmt = NULL;
36
37
    if(sqlite3_open([_databasePath UTF8String], &db) == SQLITE_OK){
38
        sqlite3_exec(db, "BEGIN TRANSACTION", 0, 0, 0);
39
40
        for (NSString* key in keys) {
41
            if(![key containsString:@"00000"]){
42
                if(sqlite3_prepare_v2(db, [[schema objectForKey:key] UTF8String], -1, &stmt, NULL) != SQLITE_OK
43
                   || sqlite3_step(stmt) != SQLITE_DONE){
44
                    *error = [NSError errorWithDomain:@"com.sqlite-sync" code:0 userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%s", sqlite3_errmsg(db)] forKey:NSLocalizedDescriptionKey]];
45
                    break;
46
                }
47
                sqlite3_reset(stmt);
48
            }
49
        }
50
51
        if(*error){
52
            sqlite3_exec(db, "ROLLBACK TRANSACTION", 0, 0, 0);
53
        }
54
        else{
55
            sqlite3_exec(db, "COMMIT", 0, 0, 0);
56
        }
57
58
        if(stmt){
59
            sqlite3_finalize(stmt);
60
        }
61
62
        sqlite3_close(db);
63
    }
64
    else{
65
        *error = [NSError errorWithDomain:@"com.sqlite-sync" code:0 userInfo:[NSDictionary dictionaryWithObject:@"Failed to open database" forKey:NSLocalizedDescriptionKey]];
66
    }
67
}
68
</code></pre>
Go to top