2013-10-24 7 views
0

이미지에 대한 URL이 포함 된 JSON 파일을 구문 분석하려고합니다. 내 코드 :Objective C 오류에서 JSON 링크 구문 분석

"링크"는 JSON 파일에서 이미지에 대한 링크입니다
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"http://my-site/pictureparse.php?name=Name"]]; 
    NSData *data= [NSData dataWithContentsOfURL:URL]; 
    if (data == nil) { 
     return; 
    } 
    NSError* error; 
    NSMutableDictionary *jsonIs = [NSJSONSerialization 
            JSONObjectWithData:data 
            options:kNilOptions 
            error:&error]; 

    NSLog(@"Json : %@",jsonIs); 
    if (jsonIs != nil) { 

     NSString *item_media = [jsonIs objectForKey:@"link"]; 

. 내가 그 개체를 구문 분석하는 NSLog에서 볼 수있는 응용 프로그램을 실행하지만 오류 얻을 때

[ 
    { 
     "link": "http://link-to-image.com/picture.jpg", 
     "title": "Title", 
     "published": "0:01 PM 24/10" 
    }, 
    { 
     "link": "http://link-to-image.com/picture.jpg", 
     "title": "Title", 
     "published": "0:01 PM 24/10" 
    }, 
    { 
     "link": "http://link-to-image.com/picture.jpg", 
     "title": "Title", 
     "published": "0:01 PM 24/10" 
    }, 
    { 
     "link": "http://link-to-image.com/picture.jpg", 
     "title": "Title", 
     "published": "0:08 PM 23/10" 
    } 
] 

:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x16e81ed0

을 어떻게이 걸릴 수 있습니다 JSON 구조는 다음과 같습니다 구문 분석 된 객체/링크를 찾아서 Instagram과 같은 피드에 표시 하시겠습니까?

나는 다음과 같은 코드를 시도하지만 작동하지 않습니다 ...

#import "PicturesViewController.h" 
#import "DemoViewController.h" 
#import "SecondViewController.h" 
#import "AppDelegate.h" 
#import "RNBlurModalView.h" 
#import "PictureJSON.h" 
#import "HMSegmentedControl.h" 

@interface PicturesViewController() 
{ 
    NSInteger refreshIndex; 
    NSArray *images; 
} 

@end 

@implementation PicturesViewController 

- (void)viewDidLoad 
{ 

    HMSegmentedControl *segmentedControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[@"Instagram", @"Hashtags", @"Facebook"]]; 
    [segmentedControl setFrame:CGRectMake(10, 10, 300, 60)]; 
    [segmentedControl addTarget:self action:@selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged]; 
    [self.view addSubview:segmentedControl]; 

    [super viewDidLoad]; 
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Menu" style:UIBarButtonItemStyleBordered target:self action:@selector(showMenu)]; 

    UIPanGestureRecognizer *gestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(swipeHandler:)]; 
    [self.view addGestureRecognizer:gestureRecognizer]; 

    [self issueLoadRequest]; 
} 

- (void)swipeHandler:(UIPanGestureRecognizer *)sender 
{ 
    [[self sideMenu] showFromPanGesture:sender]; 
} 

- (void)segmentedControlChangedValue:(HMSegmentedControl *)segmentedControl1 { 
    [self issueLoadRequest]; 
} 

- (void)segmentedControlSelectedIndexChanged:(id)sender 
{ 
    [self issueLoadRequest]; 
} 

#pragma mark - 
#pragma mark Button actions 

- (void)showMenu 
{ 
    [[self sideMenu] show]; 
} 

#pragma mark - Table view data source 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *simpleTableIdentifier = @"PictureJSON"; 

    PictureJSON *cell = (PictureJSON *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; 
    if (cell == nil) 
    { 
     NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"PictureJSON" owner:self options:nil]; 
     cell = [nib objectAtIndex:0]; 
    } 

    // The element in the array is going to be a dictionary. I JUST KNOW THIS. The key for the tweet is "text". 
    NSDictionary *tweet = [self.tweets objectAtIndex:indexPath.row]; 
    NSLog(@"%@", [cell class]); 

    UIImageView *instaImage = [[UIImageView alloc] init]; 
    instaImage.image = [tweet objectForKey:@"link"]; 

    cell.titleLabel.text = [tweet objectForKey:@"title"]; 
    cell.timeLabel.text = [tweet objectForKey:@"published"]; 

    return cell; 
} 


- (void)issueLoadRequest 
{ 
    // Dispatch this block asynchronosly. The block gets JSON data from the specified URL and performs the proper selector when done. 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
     NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://my-site.com/picutreparse.php?name=Name"]]; 
     [self performSelectorOnMainThread:@selector(receiveData:) withObject:data waitUntilDone:YES]; 
    }); 
} 

- (void)receiveData:(NSData *)data { 
    // When we have the data, we serialize it into native cocoa objects. (The outermost element from twitter is 
    // going to be an array. I JUST KNOW THIS. Reload the tableview once we have the data. 
    self.tweets = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; 
    [self.myTableView reloadData]; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return self.tweets.count; 
} 

@end 

는 정말 해결책을 부탁드립니다!

답변

1

잘못 무엇을 당신이 NSMutableDictionary

하기
NSMutableArray *jsonIs = [NSJSONSerialization 
            JSONObjectWithData:data 
            options:kNilOptions 
            error:&error]; 

    NSLog(@"Json : %@",jsonIs); 

if (jsonIs != nil) { 
NSMutableDictionary* aDict = jsonIs[0]; 
     NSString *item_media = [aDict objectForKey:@"link"]; 
} 

주 JSON 때문에 "[...]"이 배열 당신이있어 사전의 배열입니다 : "{...}"있는 tableView의 질문에 대한

편집 :

이 세계에 NSMutableArray *jsonIs을 다음의 tableview 위임에

@implementation PicturesViewController{ 
NSMutableArray *jsonIs 
} 

:

NSString *item_media = [jsonIs[indexPath.row] objectForKey:@"link"]; 
+0

좋습니다. 그것은 작동합니다. 그리고 어떻게 이것을 내 테이블보기에서 사용할 수 있습니까? @incmiko – tracifycray

+0

chech my edited 대답 – incmiko

+0

작동하지 않는 것 같습니다. 테이블보기는 시작할 때 비어 있습니다. @incmiko – tracifycray

3

문제는 사용자가 파싱에서 가져온 개체가 NSDictionary이 아닌 NSArray이고 문제가 있다는 것입니다.

편집이 하나 코드 : 마지막으로

items = [NSJSONSerialization JSONObjectWithData:data 
             options:kNilOptions 
              error:&error]; 

: 당신이 데이터를 얻는 시점에서

@interface PicturesViewController() 
{ 
    // ... 
    NSArray *items; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // ... 

    NSDictionary *item = [items objectAtIndex:indexPath.row]; 

    NSString *item_media = [item objectForKey:@"link"]; 
    // ... 
} 
+0

25 초 이전) +1 – Kuba

+0

오, 좋아. 무엇을 편집해야합니까? @tilo – tracifycray

+0

@DavidGabor : 수정 된 답변보기 – tilo