gpt4 book ai didi

objective-c - iOS 从服务器获取数据

转载 作者:行者123 更新时间:2023-11-28 17:38:13 25 4
gpt4 key购买 nike

我发现这段代码(类似,不得不调整它)关于如何从服务器获取数据,但由于某种原因它没有运行。它停在:“dispatch_async(kBgQueue, ^{”,(第 10 行)。请帮忙,我是 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

最佳答案

试试这个:

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

});

关于objective-c - iOS 从服务器获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9145136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com