Как сохранить изображения в домашнем каталоге? - PullRequest
0 голосов
/ 09 сентября 2011

Я делаю приложение, в котором я использую разбор 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];

Теперь проблема в том, что когда я возвращаюсь или забываю слово, я жду несколько секунд, чтобы вернуться к тому же виду.Теперь я хочу, чтобы я, когда приложение используется в первый раз, затем я жду этого экрана, в противном случае получаю изображения из домашнего каталога.Как мне сохранить эти изображения в моем домашнем каталоге?Как получить доступ из домашнего каталога?

Ответы [ 2 ]

0 голосов
/ 09 сентября 2011

Вы можете использовать это, чтобы записать файл в папку с документами

+(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;

}
0 голосов
/ 09 сентября 2011

Вы можете сохранить изображение в каталоге документов по умолчанию следующим образом, используя 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];
...