2013-04-24 1 views
0

json url에서 plist에 배열을 씁니다. 있는 tableView는 JSON의 URL에서 데이터를 얻을 수있을 때 인터넷의 tableview가 PLIST에서 데이터를 얻을 수 없을 때 원하는 및인터넷이 없을 때 tableView에서 데이터를 읽는 방법

이 내 코드입니다 (나는 PLIST 문서 폴더 응용 프로그램에서 파일 생성) :

#import "ViewController.h" 
#define DOC_DIR [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] 


@implementation ViewController 
{ 
    NSMutableArray *name; 
    NSMutableData *data; 
    NSString *listPath; 
    NSMutableArray *array; 
    NSArray *n; 
    NSMutableArray *add; 
} 
@synthesize table; 
-(NSString*)Dir 
{ 
    return [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES)objectAtIndex:0]; 
} 
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; 
    NSURL *url = [NSURL URLWithString:@"http://myDomain.com/test.php"]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
    NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
    [con start]; 


} 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    data = [[NSMutableData alloc]init]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData 
{ 
    [data appendData:theData]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 
    name = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; 
    for (int i = 0; i < [name count]; i++) { 

    NSIndexPath *indexPath = [self.table indexPathForSelectedRow]; 
    n = [[name objectAtIndex:(indexPath.row)+i]objectForKey:@"title"]; 
    if(!add){ 
     add = [NSMutableArray array]; 
    } 
    [add addObject:n]; 
    } 
    NSLog(@"add = %@",add); 
    [table reloadData]; 
    [self WriteToPlist:add]; 
} 
- (void)WriteToPlist:(NSArray*)dataArray 
{ 
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:dataArray,@"Name", nil]; 
    NSString *Path = [DOC_DIR stringByAppendingPathComponent:@"Plist.plist"]; 
    [dic writeToFile:Path atomically:YES]; 
    NSLog(@"Path : %@",Path); 
} 

이 코드를 JSON에서 데이터를 읽어

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    // Return the number of sections. 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    // Return the number of rows in the section. 
    return [name count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 
    cell.textLabel.text = [[name objectAtIndex:indexPath.row] objectForKey:@"title"]; 
//top code read data from json and I want when no internet read data from plist 
    return cell; 
} 

답변

0
// Path to the plist (in the application bundle) 
NSString *path = [[NSBundle mainBundle] pathForResource: 
    @"Plist" ofType:@"plist"]; 

// Build the array from the plist 
NSMutableArray *array2 = [[NSMutableArray alloc] initWithContentsOfFile:path]; 

// Show the string values 
for (NSString *str in array2) 
    NSLog(@"--%@", str); 

당신은 배열을 가지고 있고 지금은 단지 배열을

을 데이터 소스에 값을 설정 인터넷은 다음의 방법을 사용하여 연결 여부,이 방법을 구현 체크

- (BOOL) connectedToInternet 
{ 
    NSURL *requestURL = [NSURL URLWithString:@"http://www.google.com"]; 
    NSData *data = [NSData dataWithContentsOfURL:requestURL]; 

    return ([data bytes]>0) ? YES : NO; 
} 

또는

단계 :

[tableview reloadData]; 

인터넷 연결을 확인하기 위해 당신은 Reachability class provided by apple

+0

방법에는 인터넷 (방법 PLIST 파일에 액세스하지 않으려면?) 할 때있는 tableView에 표시하는 – john

+0

을 당신이 인터넷을 필요로 왜 내 친구 plist 파일의 내용에 액세스 하시겠습니까? 이것은 로컬 파일입니다. 언제든지 액세스 할 수 있습니다. – Anil

+0

@john Tableview는 연결성과 관련이 없습니다. Reachability 클래스입니다. 링크 –

0

1 단계를 사용할 수 있습니다 1 : 알고 있다면 Reachability Class를 구현하여 Apple의 인터넷 연결을 확인할 수도 있습니다.

2 단계 : 이제 Webservice를 요청 호출을 befor 당신의 방법에서 연결에 대한 점검을 확인

if([self connectedToInternet]) 
{ 
    // Make a reqeust to server 
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; 
    NSURL *url = [NSURL URLWithString:@"http://yourDomain.com/test.php"]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
    NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
    [con start]; 
} 
else 
{ 
    // Write a Handy code to load Data from Your Local Plist 
    // Path to plist From Documents Folder 
    NSString *docFilePath = [DOC_DIR stringByAppendingPathComponent:@"Data.plist"]; 

    NSDictionary *dictData = [NSDictionary dictionaryWithContentsOfFile:docFilePath]; 


    NSLog(@"%@",dictData); 
    // Reload your TableView 
} 
+0

제 친구가 도와 주실 수 있으며, 문서 폴더에서 .plist 파일을 호출하고 NSDictionary에 저장할 수있는 방법을 알려 주실 수 있습니까? – john

+0

내 코드를 편집하고 확인하십시오. –

관련 문제