-
Notifications
You must be signed in to change notification settings - Fork 6
/
MVGetRedirectedURL.m
102 lines (84 loc) · 2.62 KB
/
MVGetRedirectedURL.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#import "MVGetRedirectedURL.h"
@interface MVGetRedirectedURL () <NSURLConnectionDelegate>
@property (strong, readwrite) NSURL *url;
@property (strong, readwrite) NSURLRequest *urlRequest;
@property (strong, readwrite) NSURLConnection *urlConnection;
@property (strong, readwrite) void(^callbackBlock)(NSURL *redirectedURL, NSString *suggestedFilename);
@end
@implementation MVGetRedirectedURL
@synthesize url = url_,
urlRequest = urlRequest_,
urlConnection = urlConnection_,
callbackBlock = callbackBlock_;
- (id)initWithURL:(NSURL*)url
{
self = [super init];
if(self)
{
url_ = url;
urlRequest_ = nil;
urlConnection_ = nil;
callbackBlock_ = nil;
}
return self;
}
- (void)get:(void(^)(NSURL *redirectedURL, NSString *suggestedFilename))block
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:self.url];
[req setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[req setHTTPMethod:@"GET"];
self.urlRequest = req;
self.urlConnection = [[NSURLConnection alloc] initWithRequest:req
delegate:self];
if (!self.urlConnection)
{
block(nil, nil);
}
else
{
self.callbackBlock = block;
CFRunLoopRun();
}
});
}
#pragma mark -
#pragma mark NSURLConnectionDelegate Methods
- (NSURLRequest *)connection:(NSURLConnection *)inConnection
willSendRequest:(NSURLRequest *)inRequest
redirectResponse:(NSURLResponse *)inRedirectResponse;
{
if(inRedirectResponse)
{
NSMutableURLRequest *req = self.urlRequest.mutableCopy;
req.URL = inRequest.URL;
self.urlRequest = req;
return req;
}
return inRequest;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
dispatch_async(dispatch_get_main_queue(), ^{
self.callbackBlock(nil, nil);
});
CFRunLoopStop(CFRunLoopGetCurrent());
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.urlConnection cancel];
dispatch_async(dispatch_get_main_queue(), ^{
self.callbackBlock(self.urlRequest.URL, response.suggestedFilename);
});
CFRunLoopStop(CFRunLoopGetCurrent());
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
return nil;
}
@end