-
-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy pathMemoryOnlyURLProtocol.m
92 lines (63 loc) · 2.49 KB
/
MemoryOnlyURLProtocol.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
//
// MemoryOnlyURLProtocol.m
// Strongbox
//
// Created by Strongbox on 04/02/2022.
// Copyright © 2022 Mark McGuill. All rights reserved.
//
#import "MemoryOnlyURLProtocol.h"
#import <UIKit/UIKit.h>
@implementation MemoryOnlyURLProtocol
+ (NSString*) memoryOnlyURLProtocolScheme {
return @"strongbox-memory-only";
}
+ (void) registerMemoryOnlyURLProtocol {
static BOOL inited = NO;
if ( ! inited ) {
[NSURLProtocol registerClass:[MemoryOnlyURLProtocol class]];
inited = YES;
}
}
+ (BOOL)canInitWithRequest:(NSURLRequest *)theRequest {
slog(@"%@ received %@ with url='%@' and scheme='%@'",
self, NSStringFromSelector(_cmd),
[[theRequest URL] absoluteString], [[theRequest URL] scheme]);
NSString *theScheme = [[theRequest URL] scheme];
return ([theScheme caseInsensitiveCompare: [MemoryOnlyURLProtocol memoryOnlyURLProtocolScheme]] == NSOrderedSame );
}
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
slog(@"%@ received %@", self, NSStringFromSelector(_cmd));
return request;
}
- (void)startLoading {
slog(@"%@ received %@ - start", self, NSStringFromSelector(_cmd));
NSURLRequest *request = [self request];
NSString* theString = @"Mark is Cool!";
NSDictionary* fontAttrs =
[NSDictionary dictionaryWithObjectsAndKeys:
UIColor.redColor, NSForegroundColorAttributeName,
[UIFont systemFontOfSize:36], NSFontAttributeName,
nil];
/* calculate the size of the rendered string */
CGSize tsz = [theString sizeWithAttributes:fontAttrs];
UIGraphicsBeginImageContext(tsz);
[theString drawAtPoint:CGPointMake(0,0) withAttributes:fontAttrs];
UIImage* myImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *data = UIImageJPEGRepresentation(myImage, .75);
NSURLResponse *response =
[[NSURLResponse alloc] initWithURL:[request URL]
MIMEType:@"image/jpeg"
expectedContentLength:-1
textEncodingName:nil];
id<NSURLProtocolClient> client = [self client];
[client URLProtocol:self didReceiveResponse:response
cacheStoragePolicy:NSURLCacheStorageNotAllowed];
[client URLProtocol:self didLoadData:data];
[client URLProtocolDidFinishLoading:self];
slog(@"%@ received %@ - end", self, NSStringFromSelector(_cmd));
}
- (void)stopLoading {
slog(@"%@ received %@", self, NSStringFromSelector(_cmd));
}
@end