如何将图像保存在主目录中?

发布于 2024-12-03 18:58:08 字数 593 浏览 2 评论 0原文

我正在制作一个使用 Json 解析的应用程序。在 json 解析的帮助下,我得到了保存在字符串中的照片 url。为了在我的单元格中显示图像,我使用此代码

NSString *strURL=[NSString stringWithFormat:@"%@", [list_photo objectAtIndex:indexPath.row]];
NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: strURL]];
CGRect myImage =CGRectMake(13,5,50,50);
UIImageView *imageView = [[UIImageView alloc] initWithFrame:myImage];
[imageView setImage:[UIImage imageWithData: imageData]];
[cell addSubview:imageView];

现在的问题是,当我返回或前进时,我必须等待几秒钟才能返回相同的视图。现在我希望当应用程序第一次使用时我等待该屏幕,否则从主目录获取图像。如何将这些图像保存在我的主目录中?如何从主目录访问?

I am making an application in which i have use Json parsing. With the help of json parsing i get photo url which is saved in string. To show images in my cell i use this code

NSString *strURL=[NSString stringWithFormat:@"%@", [list_photo objectAtIndex:indexPath.row]];
NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: strURL]];
CGRect myImage =CGRectMake(13,5,50,50);
UIImageView *imageView = [[UIImageView alloc] initWithFrame:myImage];
[imageView setImage:[UIImage imageWithData: imageData]];
[cell addSubview:imageView];

Now prblem is that when i go back or forword then i have wait for few second to come back on same view. Now i want that i when application is used first tme then i wait for that screen otherwise get images from home directory. How i save these image in my home directory? How access from home directory?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柳若烟 2024-12-10 18:58:08

您可以使用 imageData 将图像保存在默认文档目录中,如下所示;

// Accessing the documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"myImage.png"];

//Writing the image file
    [imageData writeToFile:savedImagePath atomically:NO];

You can save an image in the default documents directory as follows using the imageData;

// Accessing the documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"myImage.png"];

//Writing the image file
    [imageData writeToFile:savedImagePath atomically:NO];
丿*梦醉红颜 2024-12-10 18:58:08

您可以使用它将文件写入您的文档文件夹

+(BOOL) downloadFileFromURL:(NSString *) url withLocalName:(NSString*) localName
{

    //Get the local file and it's size.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:localName];

    NSError *error;
    NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:finalPath error:&error];
    NSAssert (error == nil, ([NSString stringWithFormat:@"Error: %@", error]));
    if (error) return NO;
    int localFileSize = [[fileAttributes objectForKey:NSFileSize] intValue];


    //Prepare a request for the desired resource.
    NSMutableURLRequest *request = [NSMutableURLRequest
                                    requestWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"HEAD"];

    //Send the request for just the HTTP header.
    NSURLResponse *response;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSAssert (error == nil, ([NSString stringWithFormat:@"Error: %@", error]));
    if (error) return NO;

    //Check the response code
    int status = 404;
    if ([response respondsToSelector:@selector(statusCode)])
    {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
        status = [httpResponse statusCode];
    }
    if (status != 200)
    {
        //file not found
        return NO;
    }
    else
    {
        //file found
    }

    //Get the expected file size of the downloaded file
    int remoteFileSize = [response expectedContentLength];


    //If the file isn't already downloaded, download it.
    if (localFileSize != remoteFileSize || (localFileSize == 0))
    {       
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
        [[NSFileManager defaultManager] createFileAtPath:finalPath contents:data attributes:nil];
        return YES;
    }
    //here we may wish to check the dates or the file contents to ensure they are the same file.
    //The file is already downloaded
    return YES;
}

并读取:

+(UIImage*) fileAtLocation:(NSString*) docLocation
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:docLocation];


    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
    [[NSFileManager defaultManager] createFileAtPath:finalPath contents:data attributes:nil];

    NSData *databuffer = [[NSFileManager defaultManager] contentsAtPath:finalPath];     
    UIImage *image = [UIImage imageWithData:databuffer];
    return image;

}

You can use this to write a file to your Documents Folder

+(BOOL) downloadFileFromURL:(NSString *) url withLocalName:(NSString*) localName
{

    //Get the local file and it's size.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:localName];

    NSError *error;
    NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:finalPath error:&error];
    NSAssert (error == nil, ([NSString stringWithFormat:@"Error: %@", error]));
    if (error) return NO;
    int localFileSize = [[fileAttributes objectForKey:NSFileSize] intValue];


    //Prepare a request for the desired resource.
    NSMutableURLRequest *request = [NSMutableURLRequest
                                    requestWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"HEAD"];

    //Send the request for just the HTTP header.
    NSURLResponse *response;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSAssert (error == nil, ([NSString stringWithFormat:@"Error: %@", error]));
    if (error) return NO;

    //Check the response code
    int status = 404;
    if ([response respondsToSelector:@selector(statusCode)])
    {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
        status = [httpResponse statusCode];
    }
    if (status != 200)
    {
        //file not found
        return NO;
    }
    else
    {
        //file found
    }

    //Get the expected file size of the downloaded file
    int remoteFileSize = [response expectedContentLength];


    //If the file isn't already downloaded, download it.
    if (localFileSize != remoteFileSize || (localFileSize == 0))
    {       
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
        [[NSFileManager defaultManager] createFileAtPath:finalPath contents:data attributes:nil];
        return YES;
    }
    //here we may wish to check the dates or the file contents to ensure they are the same file.
    //The file is already downloaded
    return YES;
}

and this to read:

+(UIImage*) fileAtLocation:(NSString*) docLocation
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:docLocation];


    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
    [[NSFileManager defaultManager] createFileAtPath:finalPath contents:data attributes:nil];

    NSData *databuffer = [[NSFileManager defaultManager] contentsAtPath:finalPath];     
    UIImage *image = [UIImage imageWithData:databuffer];
    return image;

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文