-2

我想从服务器检索一个包含 10 张图像的文件夹,然后将该文件夹存储在我的文档目录中。我做了一些代码,但是当我运行它时,我得到的是图像 url,而不是图像本身。谁能帮我吗?

我的代码:

-(void)viewWillAppear:(BOOL)animated
{

NSMutableData *receivingData = [[NSMutableData alloc] init];
NSURL *url = [NSURL URLWithString:@"http://Someurl.filesCount.php"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];


   NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];

}

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{

[receivingData appendData:data];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error = nil;

{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
printf("\n the path is :%s",[path UTF8String]);


NSString *zipPath = [path stringByAppendingPathComponent:@"filesCount.php"];

[receivingData writeToFile:zipPath options:0 error:&error];



        NSString *documentsDirectoryPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"filesCount"];
        NSLog(@"the path %@",documentsDirectoryPath);



}
4

4 回答 4

1

I made this function in my previous project. You need to pass your imageView and serverUrl, then its automatically show image in your imageView and save image to temp directory, when you want again to fetch same image, then next time it take image from disk.

+(void)downloadingServerImageFromUrl:(UIImageView*)imgView AndUrl:(NSString*)strUrl{

NSFileManager *fileManager =[NSFileManager defaultManager];

NSString* theFileName = [NSString stringWithFormat:@"%@.png",[[strUrl lastPathComponent] stringByDeletingPathExtension]];
NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"tmp/%@",theFileName]];


imgView.backgroundColor = [UIColor darkGrayColor];
UIActivityIndicatorView *actView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
[imgView addSubview:actView];
[actView startAnimating];
CGSize boundsSize = imgView.bounds.size;
CGRect frameToCenter = actView.frame;
// center horizontally
if (frameToCenter.size.width < boundsSize.width)
    frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
else
    frameToCenter.origin.x = 0;

// center vertically
if (frameToCenter.size.height < boundsSize.height)
    frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
else
    frameToCenter.origin.y = 0;

actView.frame = frameToCenter;


dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{

    NSData *dataFromFile = nil;
    NSData *dataFromUrl = nil;

    dataFromFile = [fileManager contentsAtPath:fileName];
    if(dataFromFile==nil){
        dataFromUrl=[[[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:strUrl]] autorelease];
    }

    dispatch_sync(dispatch_get_main_queue(), ^{

        if(dataFromFile!=nil){
            imgView.image = [UIImage imageWithData:dataFromFile];
        }else if(dataFromUrl!=nil){
            imgView.image = [UIImage imageWithData:dataFromUrl];
            // NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"tmp/%@",theFileName]];

            BOOL filecreationSuccess = [fileManager createFileAtPath:fileName contents:dataFromUrl attributes:nil];
            if(filecreationSuccess == NO){
                NSLog(@"Failed to create the html file");
            }

        }else{
            imgView.image = [UIImage imageNamed:@"NO_Image.png"];
            imgView.tag = 105;
        }
        [actView removeFromSuperview];
        [actView release];
    });
});

}
于 2013-02-19T06:48:04.520 回答
0

如果您要在 UI 上显示从服务器加载的图像,那么

试试SDWebImageView,可以和 UIButton 或者 UIImageView 一起使用,非常简单高效。

例子,

[yourImageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
               placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

阅读如何使用它?

Okay, now for multiple images, you may need to run a loop, if you've a common base url for all your pictures (on server) something like http://yoururl/server/pictures/1.png will be replace by 2.png 3.png ... n.png, or you get different urls for pictures need to pass that url, you can load it into imageview objects, and later save them into document directory (remember, SDWebImageView by default doing this work for you). You can turn this off too.

P.S. It will load images once and stored into local (in cache) it self, next time when you pass the same image url, it won't load from server and directly load the image from local.

于 2013-02-19T06:22:22.553 回答
0

Try using this code.

 NSURL* url = [NSURL URLWithString:@"http://imageAddress.com"];
 NSURLRequest* request = [NSURLRequest requestWithURL:url];


[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
    NSData * data,
    NSError * error) {
if (!error){
        // do whatever you want with directory or store images.
    NSImage* image = [[NSImage alloc] initWithData:data];

}

}];
于 2013-02-19T06:28:27.960 回答
0

Use this code to download the image using URL and store in document directory. Iterate the logic for set of images to download and store.

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
        NSString *imageURL = @"http://sampleUrl";
        NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
        UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]];

        NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"Image1.png"]];
        if(image != NULL)
        {
            //Store the image in Document
            NSData *imageData = UIImagePNGRepresentation(image);
            [imageData writeToFile: imagePath atomically:YES];
        }
于 2013-02-19T06:41:12.983 回答