ios 以离线模式存储 URL 图像(未连接到互联网)

标签 ios xcode uiimage uibutton nsurlconnection

我正在从不同的网址获取图像数组。图像加载完美。但是如果我需要在离线模式下显示图像。我找不到正确的方法来获取它。这是我的代码

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *arr = [NSArray arrayWithObjects:[NSURL URLWithString: 
                                        @"http://images.wikia.com/marvelmovies/images/5/5e/The-hulk-2003.jpg"],
              [NSURL URLWithString:@"http://cdn.gottabemobile.com/wp-content/uploads/2012/06/ios62.jpg"],
             [NSURL URLWithString:@"http://challenge.roadef.org/2012/img/google_logo.jpg"],
              [NSURL URLWithString:@"http://addyosmani.com/blog/wp-content/uploads/2012/03/Google-doodle-of-Richard-007.jpg"],
              [NSURL URLWithString:@"http://techcitement.com/admin/wp-content/uploads/2012/06/apple-vs-google_2.jpg"],
              [NSURL URLWithString:@"http://www.andymangels.com/images/IronMan_9_wallpaper.jpg"],
              [NSURL URLWithString:@"http://sequelnews.com/wp-content/uploads/2011/11/iphone_5.jpg"],Nil];

NSURL *url=[NSURL URLWithString:arr];

NSData* theData = [NSData dataWithContentsOfURL:url];

int row = 0;
     int column = 0;

     for(int i = 0; i < [(NSArray*) url count]; ++i) {
         UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:(NSURL*)   [(NSArray*)url objectAtIndex:i]]]; 

         UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
         button.frame = CGRectMake(column*100+16, row*90, 80, 80);
         [button setImage:image forState:UIControlStateNormal]; 

         [button addTarget:self 
                    action:@selector(buttonClicked:) 
          forControlEvents:UIControlEventTouchUpInside];
         button.tag = i; 
         [self.view addSubview:button];

         if (column == 2) {
             column = 0;
             row++;
         } else {
             column++;
         }
     }      
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:arr];
[theData writeToFile:localFilePath atomically:YES];

}

请指导...

最佳答案

尝试 SDWebImage , SDWebImage 可以下载图片并存入磁盘缓存,供离线使用。

关于ios 以离线模式存储 URL 图像(未连接到互联网),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11574403/

相关文章:

iphone - LLDB 似乎没有在启动时读取我的 .lldbinit 文件

ios - 从 UIImagepickercontroller 选择后如何保存图像

ios - 将以编程方式调用的 segue 的发件人传递到目的地

ios - UIScrollView 内的 UIStackView : how to center-align stack view/items?

iphone - iOS Core 数据关系故障

ios - 如何在 CardIO 中禁用相机扫描和仅启用手动输入卡

ios - 我是否需要在 Thread 中运行 AudioServicesCreateSystemSoundID

swift - 更改项目名称后,Apple Mach-O 链接器错误

iphone - 有时 UIImageView 似乎拒绝使用 iPhone 相机拍摄的图像

ios - UITableView 中的圆形 UIImages 导致速度变慢