2012-02-04 4 views
1

서버에서 데이터를 가져 오는 방법에 대해이 코드를 (비슷하지만 조정해야 함) 발견했지만 어떤 이유로 작동하지 않습니다. 그것은에서 멈 춥니 다 : "dispatch_async(kBgQueue, ^{", (줄 10). 제발 도와, 난 IOS 프로그래밍에 아주 새로운거야.iOS 서버에서 데이터 가져 오기

#import "ViewController.h" 
@implementation ViewController 

#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1 
#define kLatestKivaLoansURL [NSURL URLWithString:  @"http://api.kivaws.org/v1/loans/search.json?status=fundraising"] //2 
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    dispatch_async(kBgQueue, ^{ 
     NSData* data = [NSData dataWithContentsOfURL: 
         kLatestKivaLoansURL]; 
     [self performSelectorOnMainThread:@selector(fetchedData:) 
           withObject:data waitUntilDone:YES]; 
    }); 
} 

- (void)fetchedData:(NSData *)responseData { 
    //parse out the json data 
    NSError* error; 
    NSDictionary* json = [NSJSONSerialization 
          JSONObjectWithData:responseData //1 

          options:kNilOptions 
          error:&error]; 

    NSArray* latestLoans = [json objectForKey:@"loans"]; //2 

    NSLog(@"loans: %@", latestLoans); //3 

    // 1) Get the latest loan 
    NSDictionary* loan = [latestLoans objectAtIndex:0]; 

    // 2) Get the funded amount and loan amount 
    NSNumber* fundedAmount = [loan objectForKey:@"funded_amount"]; 
    NSNumber* loanAmount = [loan objectForKey:@"loan_amount"]; 
    float outstandingAmount = [loanAmount floatValue] - 
    [fundedAmount floatValue]; 

    // 3) Set the label appropriately 
    humanReadble.text = [NSString stringWithFormat:@"Latest loan: % from %@ needs another $%.2f to pursue their entrepreneural dream", 
         [loan objectForKey:@"name"], 
         [(NSDictionary*)[loan objectForKey:@"location"] 
          objectForKey:@"country"], 
         outstandingAmount]; 
} 

@end 
+1

오류가 발생합니까? 그것은 조기에 종료됩니까? 그것은 어딘가에 걸려 있니? 나는 우리에게 더 많은 정보가 필요하다고 생각한다. –

답변

0

이 방법이 도움이됩니까?

__block blockSelf = self; 
dispatch_async(kBgQueue, ^{ 
    NSData* data = [NSData dataWithContentsOfURL: 
        kLatestKivaLoansURL]; 
    dispatch_async(dispatch_get_main_queue(), ^{ 
      [blockSelf fetchedData:data]; 
     }); 

}); 
+0

내 편집을 참조하십시오. 첫 번째 버전이 잘못되었습니다. – vikingosegundo

+0

확실히 청소기. 'selfForBlock' 또는'blockSafeSelf'와 같은 더 유용한 변수 이름을 제안 할 수 있을까요? –

관련 문제