1. 程式人生 > >iOS檔案系統---tmp

iOS檔案系統---tmp

tmp: 存放臨時資料,此目錄下的資料不會通過iCloud進行同步

獲取tmp的目錄

NSString *tmpPath=NSTemporaryDirectory();

下載圖片,放在Documents 下的Imgs檔案

1.建立資料夾
(
1.獲取tmp的目錄
2.拼接成我們想要的檔案目錄 , 接著進行判斷是否之前存在該路徑
3.假設不存 , 那麼進行資料夾的建立
4.判斷是否建立成功
)

-(NSString *)createDirInTmp:(NSString *)dirName{

NSString *tmpPath=NSTemporaryDirectory();
//想要的資料夾路徑
NSString *dirPath= [tmpPath stringByAppendingPathComponent:dirName]; NSFileManager *fileManager=[NSFileManager defaultManager]; if ( ![fileManager fileExistsAtPath:dirPath]) { //資料夾的建立 NSError *error; BOOL isSuccess= [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil
error:&error]; if (!isSuccess) { NSLog(@"error=%@",error.debugDescription); dirPath=nil; } } return dirPath; }

2.將圖片放入Imgs資料夾中
(
1.呼叫建立資料夾的方法 , 判斷資料夾是否為nil
2.如果資料夾不為nil 接著獲得每張圖片的路徑
3.判斷每張圖片的路徑是否之前存在
4.假設不存在,就對每張圖片的url進行編碼,防止存在中文
5.用NSDate讀取每張編碼後的圖片
6.判斷是否讀取成功
)

 NSString *imgsDocumentPath= [self createDirInTmp:@"Imgs"];

NSArray *[email protected][@"網上圖片1",@"網上圖片2"];

 if (imgsDocumentPath !=nil) {
 for (int i=0; i<imgsArray.count; i++) {

  NSString *imgsString =[imgsArray[i] lastPathComponent];
 //獲取每張圖片的路徑
 NSString *imgsPath=[imgsDocumentPath stringByAppendingPathComponent:imgsString];

NSFileManager *fileManager=[NSFileManager defaultManager];

 if (![fileManager fileExistsAtPath:imgsPath]) {
 //將每張圖片的url進行編碼(防止存在中文)
 NSString *urlString= [imgsArray[i] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

 NSData *data= [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];

  if (data==nil) {
      NSLog(@"網路有問題,請稍後再下載");
     }
     else{
       BOOL isSuccess= [data writeToFile:imgsPath atomically:YES];
       if (isSuccess) {
         NSLog(@"圖片下載成功");
       }
      else{
          NSLog(@"下載失敗");
        }
    }
   }
  }
 }