iOS簡單高效的將圖片存入沙盒,並再次調用(避坑指南)

爲了增強一些用戶體驗,防止圖片頻繁下載,或者想取用一些手機本地的照片存在程序內,我們就需要將圖片存入程序沙盒內,並在需要的時候再次調用,因爲iOS的程序每次啓動,沙盒路徑都會變,所以我們只能存儲Documents文件夾之後的路徑。

閒話少說,上代碼!

//保存圖片到沙盒內,並返回存儲圖片的後綴地址
+ (NSString *)saveImageToCacheUseImage:(UIImage *)image
{
    //獲取當前時間戳拼接到文件尾部,防止存儲圖片多時地址重複
    NSDate *currentDate = [NSDate dateWithTimeIntervalSinceNow:0];
    // *1000 是精確到毫秒,不乘就是精確到秒
    NSTimeInterval currentTime=[currentDate timeIntervalSince1970]*1000;
    NSString *timeString = [NSString stringWithFormat:@"%.0f", currentTime];
    
    //這個路徑是存儲到本地用的圖片後綴地址
    NSString *savePath= [NSString stringWithFormat:@"Documents/image_%@.png", timeString];
    //這個路徑是將圖片存入沙盒時的路徑
    NSString *imageAllPath = [NSHomeDirectory() stringByAppendingPathComponent:savePath];
    //存儲圖片到沙盒,並返回結果
    BOOL result =[UIImagePNGRepresentation(image) writeToFile:imageAllPath atomically:YES];
    
    if (result == YES) {
        NSLog(@"保存成功");
    } else {
        NSLog(@"保存失敗");
    }
    return savePath;
}

//根據圖片的後綴地址, 重新拼接完成路徑獲取圖片
+ (UIImage *)getCacheImageUseImagePath:(NSString *)imagePath
{
    //防止每次啓動程序沙盒前綴地址改變,只存儲後邊文件路徑,調用時再次拼接
    NSString *imageAllPath = [NSHomeDirectory() stringByAppendingPathComponent:imagePath];
    
    return [UIImage imageWithContentsOfFile:imageAllPath];
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章