Created
June 18, 2013 15:53
-
-
Save rs/5806542 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// EventSource.m | |
// Dailymotion | |
// | |
// Created by Olivier Poitrey on 24/09/12. | |
// Copyright (c) 2012 Dailymotion. All rights reserved. | |
// | |
#import "EventSource.h" | |
@interface EventSource () | |
@property (strong, nonatomic, readwrite) NSURL *URL; | |
@property (strong, nonatomic) void (^_dataBlock)(NSString *data); | |
@property (strong, nonatomic) NSURLConnection *_connection; | |
@property (assign, nonatomic) BOOL _autoReconnect; | |
@end | |
@implementation EventSource | |
+ (EventSource *)eventSourceWithURL:(NSURL *)URL onData:(void (^)(NSString *data))dataBlock | |
{ | |
EventSource *eventSource = EventSource.new; | |
eventSource.URL = URL; | |
eventSource._dataBlock = dataBlock; | |
[eventSource connect]; | |
return eventSource; | |
} | |
- (void)dealloc | |
{ | |
[self disconnect]; | |
} | |
- (void)connect | |
{ | |
if (self._connection && self._autoReconnect) return; | |
[self._connection cancel]; | |
self._autoReconnect = YES; | |
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:self.URL]; | |
[request setValue:@"text/event-stream" forHTTPHeaderField:@"Accept"]; | |
self._connection = [NSURLConnection connectionWithRequest:request delegate:self]; | |
} | |
- (void)disconnect | |
{ | |
self._autoReconnect = NO; | |
[self._connection cancel]; | |
} | |
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data | |
{ | |
NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; | |
for (NSString *line in [dataString componentsSeparatedByString:@"\n"]) | |
{ | |
if ([line isEqualToString:@""]) continue; | |
if ([line hasPrefix:@"data:"]) | |
{ | |
self._dataBlock([[line substringFromIndex:5] stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet]); | |
} | |
else | |
{ | |
DDLogWarn(@"unparsed line: %@", line); | |
} | |
} | |
} | |
- (void)connectionDidFinishLoading:(NSURLConnection *)connection | |
{ | |
if (self._autoReconnect) | |
{ | |
[self connect]; | |
} | |
} | |
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error | |
{ | |
if (self._autoReconnect) | |
{ | |
[self connect]; | |
} | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment