Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add request configuration block to allow customizing HTTP request #355

Merged
merged 4 commits into from
May 17, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
## master
* Add your own contributions to the next release on the line below this with your name.
- [new] Added request configuration handler to allow customizing HTTP headers per request [#355](https://github.com/pinterest/PINRemoteImage/pull/355) [zachwaugh](https://github.com/zachwaugh)
- [fixed] Moved storage of resume data to disk from memory. [garrettmoon](https://github.com/garrettmoon)
- [fixed] Hopefully fixes crashes occuring in PINURLSessionManager on iOS 9. [garrettmoon](https://github.com/garrettmoon)

Expand Down
17 changes: 17 additions & 0 deletions Source/Classes/PINRemoteImageManager.h
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,16 @@ typedef void(^PINRemoteImageManagerAuthenticationChallengeCompletionHandler)(NSU
*/
typedef void(^PINRemoteImageManagerAuthenticationChallenge)(NSURLSessionTask * __nullable task, NSURLAuthenticationChallenge * __nonnull challenge, PINRemoteImageManagerAuthenticationChallengeCompletionHandler __nullable aHandler);


/**
Request configuration handler. Used to modify a network request before it is executed.
Useful for adding custom, per-request headers.

@param request The request about to be executed
*/
typedef NSURLRequest * _Nonnull(^PINRemoteImageManagerRequestConfigurationHandler)(NSURLRequest * __nonnull request);


/**
Handler called for many PINRemoteImage tasks providing the progress of the download.

Expand Down Expand Up @@ -192,6 +202,13 @@ typedef void(^PINRemoteImageManagerProgressDownload)(int64_t completedBytes, int
*/
- (void)setValue:(nullable NSString *)value forHTTPHeaderField:(nullable NSString *)header;

/**
Sets the Request Configuration Block.

@param configurationBlock A PINRemoteImageManagerRequestConfigurationHandler block.
*/
- (void)setRequestConfiguration:(nullable PINRemoteImageManagerRequestConfigurationHandler)configurationBlock;

/**
Set the Authentication Challenge Block.

Expand Down
15 changes: 15 additions & 0 deletions Source/Classes/PINRemoteImageManager.m
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ @interface PINRemoteImageManager () <PINURLSessionManagerDelegate>
@property (nonatomic, assign) float lowQualityBPSThreshold;
@property (nonatomic, assign) BOOL shouldUpgradeLowQualityImages;
@property (nonatomic, copy) PINRemoteImageManagerAuthenticationChallenge authenticationChallengeHandler;
@property (nonatomic, copy) PINRemoteImageManagerRequestConfigurationHandler requestConfigurationHandler;
@property (nonatomic, strong) NSMutableDictionary <NSString *, NSString *> *httpHeaderFields;
#if DEBUG
@property (nonatomic, assign) float currentBPS;
Expand Down Expand Up @@ -281,6 +282,16 @@ - (void)setValue:(nullable NSString *)value forHTTPHeaderField:(nullable NSStrin
});
}

- (void)setRequestConfiguration:(PINRemoteImageManagerRequestConfigurationHandler)configurationBlock {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@zachwaugh you're right about the deadlock.

Here's what I would suggest: We need to add a getter which holds the lock when it accesses requestConfigurationHandler or else it isn't thread safe to access by clients. However, since we know we have the lock in downloadDataWithURL: we can access the ivar directly instead of using the property.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@garrettmoon sorry for the confusion, but are you saying we do need to a getter, or we don't since we can just use the direct ivar access in downloadDataWithURL:.... I made that direct ivar change and it's the only place this variable is accessed currently.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we do need a getter because the property is exposed publicly? Reading the property externally is currently not thread safe unless I'm mistaken.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The requestConfigurationHandler property isn't exposed publicly, only the setRequestConfiguration: method.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sheesh, I'm doing a terrible job reading this code for some reason. 🤦‍♂️

__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
typeof(self) strongSelf = weakSelf;
[strongSelf lock];
strongSelf.requestConfigurationHandler = configurationBlock;
[strongSelf unlock];
});
}

- (void)setAuthenticationChallenge:(PINRemoteImageManagerAuthenticationChallenge)challengeBlock {
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
Expand Down Expand Up @@ -921,6 +932,10 @@ - (NSURLSessionDataTask *)downloadDataWithURL:(NSURL *)url
request.allHTTPHeaderFields = headers;
}

if (_requestConfigurationHandler) {
request = [_requestConfigurationHandler(request) mutableCopy];
}

[NSURLProtocol setProperty:key forKey:PINRemoteImageCacheKey inRequest:request];

__weak typeof(self) weakSelf = self;
Expand Down
27 changes: 27 additions & 0 deletions Tests/PINRemoteImageTests.m
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,33 @@ - (void)testCustomRequestHeaderIsAddedToImageRequests
[self waitForExpectationsWithTimeout:[self timeoutTimeInterval] handler:nil];
}

- (void)testRequestConfigurationIsUsedForImageRequest
{
XCTestExpectation *expectation = [self expectationWithDescription:@"Requestion configuration block was called image request"];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.HTTPAdditionalHeaders = @{ @"X-Custom-Header" : @"Custom Header Value" };

self.imageManager = [[PINRemoteImageManager alloc] initWithSessionConfiguration:configuration];
[self.imageManager setRequestConfiguration:^NSURLRequest * _Nonnull(NSURLRequest * _Nonnull request) {
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[mutableRequest setValue:@"Custom Header 2 Value" forHTTPHeaderField:@"X-Custom-Header-2"];
return mutableRequest;
}];

self.imageManager.sessionManager.delegate = self;
[self.imageManager downloadImageWithURL:[self headersURL]
options:PINRemoteImageManagerDownloadOptionsNone
completion:^(PINRemoteImageManagerResult *result)
{
NSDictionary *headers = [[NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingMutableContainers error:nil] valueForKey:@"headers"];
XCTAssert([headers[@"X-Custom-Header"] isEqualToString:@"Custom Header Value"]);
XCTAssert([headers[@"X-Custom-Header-2"] isEqualToString:@"Custom Header 2 Value"]);

[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:[self timeoutTimeInterval] handler:nil];
}

- (void)testSkipFLAnimatedImageDownload
{
XCTestExpectation *expectation = [self expectationWithDescription:@"Download animated image"];
Expand Down