-
Notifications
You must be signed in to change notification settings - Fork 2
/
SBViewController.m
82 lines (64 loc) · 2.28 KB
/
SBViewController.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
//
// SBViewController.m
// ChunkedDelivery
//
// Created by Stig Brautaset on 26/04/2014.
// Copyright (c) 2014 Stig Brautaset. All rights reserved.
//
#import "SBViewController.h"
#import <SBJson5.h>
@interface SBViewController ()< NSURLSessionDataDelegate >
@property (weak) IBOutlet UITextField *urlField;
@property (weak) IBOutlet UITextView *textView;
@property (strong) SBJson5Parser *parser;
@end
@implementation SBViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)go {
NSLog(@"Go is a-go!: %@", self.urlField.text);
id block = ^(id item, BOOL *stop) {
dispatch_async(dispatch_get_main_queue(), ^{
self.textView.text = [item description];
});
};
id eh = ^(NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
self.textView.text = [NSString stringWithFormat:@"There was an error downloading: %@", error.localizedDescription];
});
};
self.parser = [SBJson5Parser unwrapRootArrayParserWithBlock:block
errorHandler:eh];
NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
delegate:self
delegateQueue:nil];
NSURL *url = [NSURL URLWithString:self.urlField.text];
NSURLSessionDataTask *urlSessionDataTask = [urlSession dataTaskWithURL:url];
[urlSessionDataTask resume];
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data {
switch ([self.parser parse:data]) {
case SBJson5ParserError:
NSLog(@"Found an error");
[session invalidateAndCancel];
self.parser = nil;
break;
case SBJson5ParserComplete:
case SBJson5ParserStopped:
self.parser = nil;
break;
case SBJson5ParserWaitingForData:
NSLog(@"Waiting for more data!");
break;
}
}
@end