ios以脱机模式存储URL图像(未连接到Internet)

时间:2012-07-20 07:01:58

标签: 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];

}

指导请...

2 个答案:

答案 0 :(得分:1)

尝试SDWebImageSDWebImage可以下载图像并保存到磁盘中以便缓存,您可以在离线状态下使用。

答案 1 :(得分:0)

您应该将图像保存到设备,以便在未连接到互联网时访问它们。你现在的方式就是加载网址。

你可以这样试试: 为每个图像使用NSData对象并在其中加载url内容。

NSData* theData = [NSData dataWithContentsOfURL:yourURLHere];

现在,您可以将此对象保存到您的设备,并在需要时随时访问它。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:@"picName.jpg"];
[theData writeToFile:localFilePath atomically:YES];

这应该是关于它的