WebPageViewController.m
11 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
//
// WebPageViewController.m
// iPhone
//
// Created by Ben Copsey on 03/10/2010.
// Copyright 2010 All-Seeing Interactive. All rights reserved.
//
#import "WebPageViewController.h"
#import "InfoCell.h"
#import "ASIWebPageRequest.h"
#import "ASIDownloadCache.h"
#import "ToggleCell.h"
#import "RequestProgressCell.h"
@implementation WebPageViewController
- (void)fetchWebPage:(id)sender
{
[self fetchURL:[NSURL URLWithString:[urlField text]]];
}
- (void)clearCache:(id)sender
{
[[ASIDownloadCache sharedCache] clearCachedResponsesForStoragePolicy:ASICacheForSessionDurationCacheStoragePolicy];
[[ASIDownloadCache sharedCache] clearCachedResponsesForStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
}
- (void)fetchURL:(NSURL *)url
{
[urlField resignFirstResponder];
[self setRequestsInProgress:[NSMutableArray array]];
[[self tableView] reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationBottom];
// This allows our ASIDownloadCache to masquerade as as NSURLCache
// It allows the webView to load the content we downloaded when replaceURLsWithDataURLs is NO
[NSURLCache setSharedURLCache:[ASIDownloadCache sharedCache]];
[request setDelegate:nil];
[request cancel];
[self setRequest:[ASIWebPageRequest requestWithURL:url]];
[request setDidFailSelector:@selector(webPageFetchFailed:)];
[request setDidFinishSelector:@selector(webPageFetchSucceeded:)];
[request setDelegate:self];
[request setDownloadProgressDelegate:self];
[request setShowAccurateProgress:NO];
[request setReplaceURLsWithDataURLs:[replaceURLsSwitch isOn]];
// It is strongly recommended that you set both a downloadCache and a downloadDestinationPath for all ASIWebPageRequests
[request setDownloadCache:[ASIDownloadCache sharedCache]];
[request setDownloadDestinationPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"webpage"]];
[[ASIDownloadCache sharedCache] setShouldRespectCacheControlHeaders:NO];
[request startAsynchronous];
}
- (void)webPageFetchFailed:(ASIHTTPRequest *)theRequest
{
[responseField setText:[NSString stringWithFormat:@"Something went wrong: %@",[theRequest error]]];
}
- (void)webPageFetchSucceeded:(ASIHTTPRequest *)theRequest
{
if ([theRequest downloadDestinationPath]) {
NSString *response = [NSString stringWithContentsOfFile:[theRequest downloadDestinationPath] encoding:[theRequest responseEncoding] error:nil];
[responseField setText:response];
[webView loadHTMLString:response baseURL:[theRequest url]];
} else {
[responseField setText:[theRequest responseString]];
[webView loadHTMLString:[theRequest responseString] baseURL:[theRequest url]];
}
[urlField setText:[[theRequest url] absoluteString]];
}
// We'll take over the page load when the user clicks on a link
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)theRequest navigationType:(UIWebViewNavigationType)navigationType
{
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
[self fetchURL:[theRequest URL]];
return NO;
}
return YES;
}
// At time of writing ASIWebPageRequests do not support automatic progress tracking across all requests needed for a page
// The code below shows one approach you could use for tracking progress - it creates a new row with a progress indicator for each resource request
// However, you could use the same approach and keep track of an overal total to show progress
- (void)requestStarted:(ASIWebPageRequest *)theRequest
{
[[self requestsInProgress] addObject:theRequest];
[[self tableView] beginUpdates];
[[self tableView] insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:[[self requestsInProgress] count]-1 inSection:2]] withRowAnimation:UITableViewRowAnimationBottom];
[[self tableView] endUpdates];
}
- (void)request:(ASIHTTPRequest *)theRequest didReceiveBytes:(long long)newLength
{
NSInteger requestNumber = [[self requestsInProgress] indexOfObject:theRequest];
if (requestNumber != NSNotFound) {
RequestProgressCell *cell = (RequestProgressCell *)[[self tableView] cellForRowAtIndexPath:[NSIndexPath indexPathForRow:requestNumber inSection:2]];
[[cell progressView] setProgress:[theRequest totalBytesRead]/([theRequest contentLength]+[theRequest partialDownloadSize])];
}
}
- (void)request:(ASIHTTPRequest *)theRequest incrementDownloadSizeBy:(long long)newLength
{
[self request:theRequest didReceiveBytes:0];
}
/*
Most of the code below here relates to the table view, and isn't that interesting
*/
- (void)dealloc
{
[request setDelegate:nil];
[request cancel];
[request release];
[webView setDelegate:nil];
[webView release];
[responseField release];
[urlField release];
[super dealloc];
}
- (void)viewDidLoad
{
[[[self navigationBar] topItem] setTitle:@"Downloading a Web Page"];
webView = [[UIWebView alloc] initWithFrame:CGRectZero];
[webView setDelegate:self];
responseField = [[UITextView alloc] initWithFrame:CGRectZero];
[responseField setBackgroundColor:[UIColor clearColor]];
[responseField setEditable:NO];
[responseField setText:@"HTML source will appear here"];
urlField = [[UITextField alloc] initWithFrame:CGRectZero];
[urlField setBorderStyle:UITextBorderStyleRoundedRect];
[urlField setText:@"http://allseeing-i.com/ASIHTTPRequest/tests/ASIWebPageRequest/index.html"];
[[self view] setAutoresizingMask:UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth];
}
static NSString *intro = @"ASIWebPageRequest lets you download complete webpages, including most of their external resources. ASIWebPageRequest can download stylesheets, javascript files, images (including those referenced in CSS), frames, iframes, and HTML 5 audio and video.\r\n\r\nExternal resources can be made available to a UIWebView by setting your ASIDownloadCache to be NSURLCache's default cache. Alternatively, you can set ASIWebPageRequest to replace urls of external files with their actual data. This lets you save a complete web page as a single file.\r\n\r\nASIWebPageRequest is NOT intended to be a drop-in replacement for UIWebView's regular loading mechanism. It is best used for getting more control over caching web pages you control, or for displaying web page content that requires more complex authentication (eg NTLM).\r\n\r\nIt is strongly recommended that you use ASIWebPageRequest in conjunction with a downloadCache, and you should always set a downloadDestinationPath for all ASIWebPageRequests.\r\n\r\nTo use ASIWebPage request, you must link with libxml, and add '${SDK_DIR}/usr/include/libxml2' to your Header Search Paths.";
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
int tablePadding = 40;
int tableWidth = [tableView frame].size.width;
if (tableWidth > 480) { // iPad
tablePadding = 110;
}
UITableViewCell *cell;
if ([indexPath section] == 0) {
cell = [tableView dequeueReusableCellWithIdentifier:@"InfoCell"];
if (!cell) {
cell = [InfoCell cell];
}
[[cell textLabel] setText:intro];
[cell layoutSubviews];
} else if ([indexPath section] == 1) {
if ([indexPath row] == 0) {
cell = [tableView dequeueReusableCellWithIdentifier:@"WebPageCell"];
if (!cell) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"WebPageCell"] autorelease];
[[cell contentView] addSubview:webView];
}
[webView setFrame:CGRectMake(10,10,tableWidth-tablePadding,280)];
} else {
cell = [tableView dequeueReusableCellWithIdentifier:@"ToggleCell"];
if (!cell) {
cell = [ToggleCell cell];
}
[[cell textLabel] setText:@"Replace URLs with Data"];
replaceURLsSwitch = [(ToggleCell *)cell toggle];
}
} else if ([indexPath section] == 2) {
cell = [tableView dequeueReusableCellWithIdentifier:@"RequestProgressCell"];
if (!cell) {
cell = [RequestProgressCell cell];
}
ASIHTTPRequest *theRequest = [[self requestsInProgress] objectAtIndex:[indexPath row]];
[[cell textLabel] setText:[[theRequest url] absoluteString]];
if ([theRequest contentLength] > 0) {
[[(RequestProgressCell *)cell progressView] setProgress:[theRequest totalBytesRead]/([theRequest contentLength]+[theRequest partialDownloadSize])];
}
} else if ([indexPath section] == 3) {
cell = [tableView dequeueReusableCellWithIdentifier:@"Response"];
if (!cell) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Response"] autorelease];
[[cell contentView] addSubview:responseField];
}
[responseField setFrame:CGRectMake(5,5,tableWidth-tablePadding,180)];
}
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell;
}
- (UIView *)tableView:(UITableView *)theTableView viewForHeaderInSection:(NSInteger)section
{
if (section == 1) {
int tablePadding = 40;
int tableWidth = [tableView frame].size.width;
if (tableWidth > 480) { // iPad
tablePadding = 110;
}
UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0,0,tableWidth-(tablePadding/2),30)] autorelease];
UIButton *clearCacheButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[clearCacheButton setTitle:@"Clear Cache" forState:UIControlStateNormal];
[clearCacheButton sizeToFit];
[clearCacheButton setFrame:CGRectMake([view frame].size.width-[clearCacheButton frame].size.width+10,7,[clearCacheButton frame].size.width,[clearCacheButton frame].size.height)];
[clearCacheButton addTarget:self action:@selector(clearCache:) forControlEvents:UIControlEventTouchDown];
[view addSubview:clearCacheButton];
UIButton *goButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[goButton setTitle:@"Go!" forState:UIControlStateNormal];
[goButton sizeToFit];
[goButton setFrame:CGRectMake([clearCacheButton frame].origin.x-[goButton frame].size.width-10,7,[goButton frame].size.width,[goButton frame].size.height)];
[goButton addTarget:self action:@selector(fetchWebPage:) forControlEvents:UIControlEventTouchDown];
[view addSubview:goButton];
[urlField setFrame:CGRectMake((tablePadding/2)-10,8,tableWidth-tablePadding-160,34)];
[view addSubview:urlField];
return view;
}
return nil;
}
- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section
{
if (section == 1) {
return 2;
} else if (section == 2) {
return [requestsInProgress count];
}
return 1;
}
- (CGFloat)tableView:(UITableView *)theTableView heightForHeaderInSection:(NSInteger)section
{
if (section == 1) {
return 50;
}
return 34;
}
- (CGFloat)tableView:(UITableView *)theTableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([indexPath section] == 0) {
return [InfoCell neededHeightForDescription:intro withTableWidth:[tableView frame].size.width]+20;
} else if ([indexPath section] == 1) {
if ([indexPath row] == 0) {
return 300;
} else {
return 50;
}
} else if ([indexPath section] == 3) {
return 200;
} else {
return 34;
}
}
- (NSString *)tableView:(UITableView *)theTableView titleForHeaderInSection:(NSInteger)section
{
return nil;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 4;
}
@synthesize request;
@synthesize requestsInProgress;
@end