Вот мой код, как скачать изображение с URL-адреса и сохранить его в каталоге документов, используя AFNetworking.Как показать изображение в UIImageView из кеша, используя AFNetworking?
Теперь, мой вопрос: если изображение уже загружено с URL-адреса, тогда изображение загружается из кеша вместо его повторной загрузки. Я хочу сделать это, используя AFNetworking. Я знаю, что решение этой проблемы находится внутри #import "UIKit+AFNetworking/UIKit+AFNetworking.h"
Если у кого-нибудь есть идеи, как помочь, пожалуйста, помогите мне решить мою проблему.
#import "ViewController.h"
#define URL @"https://upload.wikimedia.org/wikipedia/commons/e/ec/USA-NYC-American_Museum_of_Natural_History.JPG"
@interface ViewController()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.progressBar.hidden = YES ;
self.lblProgressStatus.hidden = YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)Action:(UIButton *)sender
{
self.progressBar.hidden = NO ;
self.lblProgressStatus.hidden = NO ;
self.ActionDownload.enabled = NO ;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *strURL = [NSURL URLWithString:URL];
NSURLRequest *request = [NSURLRequest requestWithURL:strURL];
NSProgress *progress;
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response)
{
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
}
completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error)
{
[self.progressBar setHidden:YES];
self.lblProgressStatus.text = @"Download completed" ;
NSLog(@"File downloaded to: %@", filePath);
NSString * strTemp = [NSString stringWithFormat:@"%@", filePath];
NSArray *components = [strTemp componentsSeparatedByString:@"/"];
id obj = [components lastObject];
NSLog(@"%@", obj);
NSString *docPath = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
NSString *strFilePath = [NSString stringWithFormat:@"%@/%@",docPath, obj];
BOOL fileExists=[[NSFileManager defaultManager] fileExistsAtPath:strFilePath];
if (!fileExists)
{
NSLog(@"File Not Found");
}
else
{
UIImage * image = [UIImage imageWithContentsOfFile:strFilePath];
self.imageView.image = image ;
}
[progress removeObserver:self forKeyPath:@"fractionCompleted" context:NULL];
}];
[self.progressBar setProgressWithDownloadProgressOfTask:downloadTask animated:YES];
[downloadTask resume];
[progress addObserver:self
forKeyPath:NSStringFromSelector(@selector(fractionCompleted)) options:NSKeyValueObservingOptionNew
context:NULL];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"fractionCompleted"])
{
NSProgress *progress = (NSProgress *)object;
int temp = progress.fractionCompleted * 100 ;
// NSLog(@"%d", temp);
NSString * strTemp = @"%";
dispatch_async(dispatch_get_main_queue(), ^{
// Update the UI
self.lblProgressStatus.text = [NSString stringWithFormat:@"%d %@", temp, strTemp];
});
}
else
{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
@end
извините, но я не получаю ответа. –
Вы хотите загрузить изображение (либо из кеша, либо из URL-адреса) и сохранить его локально? Или я вас неправильно понял? Вы можете использовать UIImageView + AFNetworking.h? – aramusss
В приведенном выше коде мое изображение сохраняется в каталоге документов, теперь, когда оно загружается, оно извлекает изображение из кеша, а не собирается загружать его. и я хочу сделать это с помощью #import "UIKit + AFNetworking/UIKit + AFNetworking.h" –