2014-09-08 6 views
0

기사를 읽는 앱을 만들고 있어요. JSON 형식의 서버에서 데이터를 가져 와서 UITableView에로드하고 UIWebView에로드합니다.
기사에는 이미지, 비디오 및 텍스트가 포함되어 있습니다. 오프라인 캐싱은 이전에로드 된 기사를 읽을 수있는 인터넷 사용자가없는 경우를 의미합니다. 이미지에 비동기 스레드가 사용되었습니다. 당신은 하나 개의 SQLite는 파일을 데이터베이스로 JSON에서 얻는 모든 세부 사항을 저장해야iOS에서 오프라인으로 문서 캐싱 기사를 구현하려면 어떻게해야하나요?

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    [self checkInternetConnection]; 
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20,10,0,20)]; 
    titleLabel.textColor = [UIColor blackColor]; 
    titleLabel.backgroundColor = [UIColor clearColor]; 
    titleLabel.text = @"Story"; 
    [self.navigationItem setTitleView:titleLabel]; 

    UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; 
    spinner.center = CGPointMake(160, 240); 
    spinner.hidesWhenStopped = YES; 
    [self.view addSubview:spinner]; 
    [spinner startAnimating]; 
    BOOL myBool = [self isNetworkAvailable]; 
    if (myBool) 
    { 
     @try { 

      self.tableView.separatorColor = [UIColor colorWithRed:190/255.0 green:190/255.0 blue:190/255.0 alpha:1.0]; 

      // for displaying the previous screen lable with back button in details view controller  UIBarButtonItem *backbutton1 = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:nil action:nil]; 
      [[self navigationItem] setBackBarButtonItem:backbutton1]; 
      _Title1 = [[NSMutableArray alloc] init]; 
      _Author1 = [[NSMutableArray alloc] init]; 
      _Images1 = [[NSMutableArray alloc] init]; 
      _Details1 = [[NSMutableArray alloc] init]; 
      _link1 = [[NSMutableArray alloc] init]; 
      _Date1 = [[NSMutableArray alloc] init]; 
      pageNumber=1; 
      NSData* data = [NSData dataWithContentsOfURL:ysURL]; 
      NSArray *ys_avatars = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 
      if(ys_avatars){ 
       for (int j=0;j<ys_avatars.count;j++) 
       { 
        [_Title1 addObject:ys_avatars[j][@"title"]]; 
        [_Author1 addObject: ys_avatars[j][@"author"]]; 
        [_Images1 addObject: ys_avatars[j][@"featured_img"]]; 
        [_Details1 addObject:ys_avatars[j][@"content"]]; 
        [_link1 addObject:ys_avatars[j][@"permalink"]]; 
        NSString *newStr=[ys_avatars[j][@"date"] substringToIndex:[ys_avatars[j]  [@"date"] length]-3]; 
        [_Date1 addObject:newStr]; 
       } 
      } 
      else 
      { 
       NSLog(@"asd"); 
      } 
     } 
     @catch (NSException *exception) { 

     } 
     dispatch_queue_t downloadQueue = dispatch_queue_create("downloader", NULL); 
     dispatch_async(downloadQueue, ^{ 
      // do our long running process here 
      [NSThread sleepForTimeInterval:3]; 
      // do any UI stuff on the main UI thread 
      dispatch_async(dispatch_get_main_queue(), ^{ 
       [spinner stopAnimating]; 
      }); 
     }); 
    } 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView 
     cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *Cellidentifier1 = @"ysTableViewCell"; 
    ysTableViewCell *cell1 = [tableView  dequeueReusableCellWithIdentifier:Cellidentifier1 forIndexPath:indexPath]; 
    long row = [indexPath row]; 
    cell1.TitleLabel1.text = _Title1[row]; 
    cell1.AuthorLabel1.text = _Author1[row]; 
    NSString *yourStoryUrl = [_Images1[indexPath.row] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; 
    if(yourStoryUrl) { 
     NSArray *subStringsUrl = [yourStoryUrl componentsSeparatedByString:@"/"]; 
     NSString *stripedName = [subStringsUrl lastObject]; 
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
     NSString *documentsDirectory = [paths objectAtIndex:0]; 
     NSString* filePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",stripedName]]; 
     NSLog(@"File Path retrieved %@", filePath); 
     if(filePath) { 
      UIImage *image = [UIImage imageWithContentsOfFile:filePath]; 
      if(image) { 
       ysTableViewCell *updateCell =(id)[tableView cellForRowAtIndexPath:indexPath]; 
       if(updateCell) 
        updateCell.ThumbImage1.image=image; 
       cell1.ThumbImage1.image=image; 
      } else { 
       dispatch_queue_t taskQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 
       dispatch_async(taskQ, ^{ 
        NSURL *Imageurl = [NSURL URLWithString:yourStoryUrl]; 
        NSData *data = [NSData dataWithContentsOfURL:Imageurl]; 
        UIImage *images1 = [[UIImage alloc] initWithData:data]; 
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
        NSString *documentsDirectory = [paths objectAtIndex:0]; 
        NSData *imageData = UIImagePNGRepresentation(images1); 
        //_imagePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",stripedName]]; 
        if (![imageData writeToFile:filePath atomically:NO]) 
        { 
         NSLog((@"Failed to cache image data to disk")); 
        } 
        else 
        { 
         NSLog((@"the cachedImagedPath is %@",filePath)); 
        } 
        dispatch_sync(dispatch_get_main_queue(), ^{ 
         ysTableViewCell *updateCell =(id)[tableView cellForRowAtIndexPath:indexPath]; 
         if(updateCell) 
          updateCell.ThumbImage1.image=images1; 
         cell1.ThumbImage1.image=images1; 
        }); 
       }); 
       return cell1; 
      } 

답변

0

오프라인 매장의 경우 :

여기 내 코드입니다. 데이터베이스에는 이미지와 비디오의 파일 경로 만 저장하십시오. 해당 자산을 다운로드하여 문서 디렉토리에 저장하십시오.

감사합니다.

0

당신은 키 입력 아카이브를 사용할 수는 (NSKeyedArchiver/NSKeyedUnarchiver)

다음

tutorial

입니다