0

我开发了 iOS 应用程序,我在其中从服务器下载图像并将其保存在我的 Document 目录中。

但我面临的问题是,有时我的图像在下载时会损坏,即使服务器响应是成功的。

这是我的代码片段,

urlFile 是服务器上 UIImage 的路径,例如:www.abcd.com/images/pqr.jpg

我用于在我的 DocDirectory 中保存图像名称的文件名。

- (void)downloadFile:(NSString *)urlFile withName:(NSString *)fileName 
{
    NSString *trimmedString = [urlFile stringByTrimmingCharactersInSet:
                               [NSCharacterSet whitespaceAndNewlineCharacterSet]];

    NSLog(@"trimmedString=%@",trimmedString);
    if ([trimmedString length]>0)
    {
        HTTPEaterResponse *response = [HTTPEater get:[NSString stringWithFormat:@"%@",trimmedString]];

    if ([response isSuccessful])
        {  
           NSLog(@"isSuccessful");
            [self saveImage:[[UIImage alloc] initWithData:[response body]] withName:fileName];
        } else {
            NSLog(@"Url response failed %@", [response description]);
        }
    }

}


    - (void)saveImage:(UIImage *)image withName:(NSString *)name
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        NSData *data = UIImagePNGRepresentation(image);
        NSLog(@"image =%@",image);

        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
        [fileManager createFileAtPath:fullPath contents:data attributes:nil];

    }

当我看到我的日志时,它显示:

  • trimmedString= www.abcd.com/images/pqr.jpg
  • 是成功的
  • 图像=空

提前致谢。

4

5 回答 5

2

我使用以下代码,它适用于我。

NSData *thumbImageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:ImageURL]];
[thumbImageData writeToFile:cachedThumbnailFileName atomically:YES];
UIImage * image =  [UIImage imageWithContentsOfFile:cachedThumbnailFileName];
imageView.image = image;

希望它可以帮助你。:)

于 2013-09-24T07:24:05.543 回答
1

要将图像保存在目录中,请使用:

NSString  *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.jpg"];
[UIImagePNGRepresentation(selectedImage) writeToFile:pngPath atomically:YES];
NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];  
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
于 2013-09-19T06:10:04.627 回答
0

相反,您可以使用“NSURLRequest”和“NSURLConnection”,例如,如果您获得图像 URL,

    NSURL* aURL = [NSURL URLWithString:trimmedString];//get the url of string
    NSURLRequest *aReq = [NSURLRequest requestWithURL:aURL];
    NSURLConnection *aConnection = [NSURLConnection connectionWithRequest:aReq delegate:self]; //get a connection to url , since it confirms to delegate u need to implement delegate methods 
    if(aConnection == nil) //if it is nil then cancel and close the request
    { 
       aConnection = nil;  
      [aConnection cancel];
    }


   // after this implement this delegate methods
  - (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)received_data
  {
      if(image_data == nil)    //if data is not initialised initialise it
      {
          image_data = [[NSMutableData alloc]init];
      }

      [self.image_data appendData:received_data];//append the received data

  }
  //this method is called after successful download of the image
  - (void)connectionDidFinishLoading:(NSURLConnection *)connection;
 {
    // UIImage* sampleImage = [UIImage imageWithData:self.image_data];
    // self.image = sampleImage; //convert the data to image 
    //since u hav complete downloaded date in "self.image_data"

    NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"/myImage.png"];//set the name of the image and path may it saving in application directory check it out  
    [self.image_data writeToFile:imagePath atomically:YES]; //saving the data with name
 }

希望这对你有帮助:)

于 2013-09-12T11:00:05.863 回答
0

你记录了回复[response body]吗?

只需尝试将该响应转换为NSData然后另存为图像。使用Base64Encoding类,您可以将响应转换为base64Data

NSData *imageData = [NSString base64DataFromString:[response body]];
[self saveImage:[[UIImage alloc] initWithData:imageData] withName:fileName];
于 2013-09-12T10:53:42.010 回答
0

我建议你使用 SDWebimage 类SDWebimage下载.. 我认为它对你很有帮助,即使我总是更喜欢 SDWebimage 库。这是一些事情。

An UIImageView category adding web image and cache management to the Cocoa Touch framework
An asynchronous image downloader
An asynchronous memory + disk image caching with automatic cache expiration handling
Animated GIF support
WebP format support
A background image decompression
A guarantee that the same URL won't be downloaded several times
A guarantee that bogus URLs won't be retried again and again
A guarantee that main thread will never be blocked
Performances!
Use GCD and ARC
于 2013-09-19T06:24:20.843 回答