网上搜到的关于SDWebImage 添加 token,亦或者 SDWebImage add header的方法,都是直接使用SDWebImageDownloader
中的setValue:forHTTPHeaderField:
方法来设置。但是设置了之后笔者这边图片还是出不来,仔细研究后发现笔者这边的图片显示是先经过一次302跳转,然后跳转后才是真正的图片链接,第二次的这个链接是需要 token 的。
而直接设置SDWebImageDownloader
的HTTPHeaderField
设置到了第一个链接上面,302重定向后第二个链接的HTTPHeaderField
仍是没有 token
一般来说,直接使用SDWebImageDownloader
中的setValue:forHTTPHeaderField:
方法设置即可。如下:
- (void)addSDWebImageToken {
SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader];
NSString *tokenString =[[NSUserDefaults standardUserDefaults]valueForKey:YourToken];
tokenString = [NSString stringWithFormat:@"Bearer %@",tokenString];
[downloader setValue:tokenString forHTTPHeaderField:@"Authorization"];
}
对于经过302重定向的链接,则需要如下修改:
打开SDWebImageDownloader.m
类,修改- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler
方法如下:
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler {
// Identify the operation that runs this task and pass it the delegate method
NSOperation<SDWebImageDownloaderOperation> *dataOperation = [self operationWithTask:task];
NSMutableURLRequest *customRequest = [[NSMutableURLRequest alloc] initWithURL:request.URL];
customRequest.allHTTPHeaderFields = self.HTTPHeaders;
if ([dataOperation respondsToSelector:@selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)]) {
[dataOperation URLSession:session task:task willPerformHTTPRedirection:response newRequest:customRequest completionHandler:completionHandler];
} else {
if (completionHandler) {
completionHandler(customRequest);
}
}
}
原理:简单的说是把 重定向的request 变为 CustomRequest, 然后给 CustomRequest 添加 header,最后回调 CustomRequest,而给 CustomRequest 设置 Header的方法,是使用SDWebImageDownloader
中setValue:forHTTPHeaderField:
设置的。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。