2012-03-17 18 views
5

Tôi đang cố gắng lấy đầu của mình xung quanh NSJSONSerialization Class Reference. Trong việc thiếu một ví dụ mã tại trang web developer.apple.com, tôi đã mất. Có hàng triệu ví dụ trên toàn bộ web với các libarie json khác, nhưng tôi chưa thể có được bất kỳ thứ gì trong số chúng để làm việc với bản dựng xcode mới nhất. (Tôi đang chạy: Phiên bản 4.3.1 (4E1019) và thử nghiệm trên iPhone 5.0.1)Làm cách nào để tìm nạp dữ liệu từ URL, sử dụng xcode 4.3.1 với Tham chiếu lớp NSJSONSerialization

Tôi muốn tìm nạp dữ liệu từ tệp json vào iphone của tôi bằng nút.

phép nói rằng tôi nhận được dữ liệu của tôi từ URL: http://companyurl/jsonfile.json (tiêu chuẩn JSON-format)

Các jsonfile.json trông somthing như thế này ...;

{ 
    "companylist": 
[ 
     { 
     "company":"Companyname 1", 
     "telephone":"1234567890", 
     "url":"http:\/\/www.companyname1.com\/", 
     "category":"category 1", 
     "position":"1", 
     }, 
     { 
     "company":"Companyname 2", 
     "telephone":"2345678901", 
     "url":"http:\/\/www.companyname2.com\/", 
     "category":"category 2", 
     "position":"2", 
     }, 
     { 
     "company":"Companyname 3", 
     "telephone":"3456789012", 
     "url":"http:\/\/www.companyname3.com\/", 
     "category":"category 3", 
     "position":"3", 
     } 
] 
} 

Tôi nên viết gì trong tệp .h và tệp .m của mình?

Cảm ơn bạn đã trợ giúp! :)

+0

Nó giúp để tìm kiếm trước khi hỏi: [cách sử dụng NSJSONSerialization] (http://stackoverflow.com/questions/8356842 /), [truy xuất dữ liệu từ url] (http://stackoverflow.com/questions/2034066/) – rickster

Trả lời

7

Thanks guys. Tôi đã hiểu rồi. (... và đây là những gì tôi đã làm :)

Trong file .m tôi thêm mã này:

- (IBAction)getDataFromJson:(id)sender { 
     NSURL *url = [NSURL URLWithString:@"http://yourwebsite.com/jsonfile.json"]; 

     NSData *jsonData = [NSData dataWithContentsOfURL:url]; 


     if(jsonData != nil) 
     { 
      NSError *error = nil; 
      id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error]; 
      if (error == nil) 
       NSLog(@"%@", result); 
} 
} 

Trong file .h của tôi, tôi đã thêm mã này:

@interface ViewController : UIViewController 
- (IBAction)getDataFromJson:(id)sender; 
15
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://your_web_server/your_file...."]]; 
NSError *error=nil; 
id response=[NSJSONSerialization JSONObjectWithData:data options: 
           NSJSONReadingMutableContainers error:&error]; 

NSLog(@"Your JSON Object: %@ Or Error is: %@", response, error); 

Chú ý: Mã này hoạt động trên Xcode 4.2 với iOS 5.01 trên mô phỏng và 5.1 trên thiết bị iPad tại thời điểm

+0

là id , không phải id * – hop

1

Không bao giờ EVER sử dụng dataWithContentsOfURL: để lấy dữ liệu máy chủ theo cách này. Nó không kiểm soát được và có thể để ứng dụng của bạn ở trạng thái không xác định. Bạn nên, ở mức tối thiểu, được thực hiện tất cả các cuộc gọi url với NSURLRequest. Tốt hơn, nếu bạn không hỗ trợ trước iOS7, hãy sử dụng NSURLSession.

0
jsonDict = [[NSDictionary alloc] init]; 
    data = [[NSArray alloc] init]; 

     url =[NSURLURLWithString:@"Please Type Your URL "]; 


// Parse the JSON data from the given URL 
    - (void) parseJSONWithURL:(NSURL *) jsonURL 
    { 
// Set the queue to the background queue. We will run this on the background thread to keep 
// the UI Responsive. 
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0); 

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; 

// Run request on background queue (thread). 
     dispatch_async(queue, ^{ 
     NSError *error = nil; 

    // Request the data and store in a string. 
     NSString *json = [NSString stringWithContentsOfURL:jsonURL 
               encoding:NSASCIIStringEncoding 
               error:&error]; 
     if (error == nil){ 

     // Convert the String into an NSData object. 
     NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding]; 

     // Parse that data object using NSJSONSerialization without options. 
     jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error]; 

     // Parsing success. 
     if (error == nil) 
     { 
      // Go back to the main thread and update the table with the json data. 
      // Keeps the user interface responsive. 
      dispatch_async(dispatch_get_main_queue(), ^{ 
       [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 
       data= [[jsonDict valueForKey:@"Result"] valueForKey:@"data"]; 
       [jsonTable reloadData]; 
      }); 
     } 

     // Parsing failed, display error as alert. 
     else 
     { 
      UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"Uh Oh, Parsing Failed." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil]; 

      [alertView show]; 
     } 
    } 

    // Request Failed, display error as alert. 
    else 
    { 
     UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"Request Error! Check that you are connected to wifi or 3G/4G with internet access." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil]; 

     [alertView show]; 
     } 
    }); 
    } 


// Delegate call back for cell at index path. 
    - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"]; 

    if (cell == nil) 
    { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MainCell"]; 
} 

// Set the main label as the episode name. 
    cell.textLabel.text = [[data objectAtIndex:indexPath.row] objectForKey:@"fullname"]; 




    NSNumber *seasonNum = [[data objectAtIndex:indexPath.row] objectForKey:@"username"]; 
    NSNumber *episodeNum = [[data objectAtIndex:indexPath.row] objectForKey:@"location"]; 
    NSMutableString *seasonEpisodeNum = [NSMutableString stringWithFormat:@"username: %@ ", seasonNum]; 
    [seasonEpisodeNum appendString:[NSMutableString stringWithFormat:@"location: %@", episodeNum]]; 
    cell.detailTextLabel.text = seasonEpisodeNum; 

    return cell; 
    } 






    -(int) numberOfSectionsInTableView:(UITableView *) tableView 
    { 
    return 1; 
    } 


    - (int) tableView:(UITableView *) tableView numberOfRowsInSection: (NSInteger)section 
    { 
return [data count]; 
} 

mã này thực hiện tập tin .m

và file .h

{ 
     NSDictionary *jsonDict; 
     IBOutlet UITableView *jsonTable; 
     NSArray *data; 
     NSURL *url; 
    } 
Các vấn đề liên quan