【问题标题】:Fetching Wordpress JSON data via URL for an iOS app通过 URL 获取 iOS 应用程序的 Wordpress JSON 数据
【发布时间】:2015-03-02 06:34:02
【问题描述】:

我目前正在使用以下代码从我的 iOS 应用程序中的静态 JSON 文件中提取数据:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

navigationController.delegate = self;

NSString* jsonFile = [[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"/app.json"];
NSString* jsonString = [NSString stringWithContentsOfFile:jsonFile encoding:NSUTF8StringEncoding error:nil];
@try {
    RootViewController* rootViewController = (RootViewController*)[navigationController.viewControllers objectAtIndex:0];
    rootViewController.feed = [[jsonString JSONValue] objectForKey:@"thefeed"];
    [self.window addSubview:navigationController.view];
}

@catch (NSException * e) { }

[self.window makeKeyAndVisible];

return YES;

}

它就像我希望它用于静态数据一样工作,但我需要它通过实时 url 动态工作。我正在使用 Wordpress REST API 来踢出我想要的 JSON:http://milknsugar.com/wp-json/posts?filter[posts_per_page]=50&filter[order]=DESC

我尝试了以下几种变体,但运气不佳:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
navigationController.delegate = self;

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:MILKNSUGAR_URL]];
NSURLConnection* Connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (Connection)
    self.feed = [NSMutableData data];

[self.window addSubview:loadingView];
[self.window makeKeyAndVisible];

return YES;

}

有什么建议或建议吗?谢谢!

【问题讨论】:

标签: ios json wordpress rest feed


【解决方案1】:

我认为这将解决您的问题。取一个变量

@property(nonatomic,strong)NSMutableData *dataReceived;

并将此代码写入您要发送请求的任何位置。

NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:MILKNSUGAR_URL]];
NSURLConnection *conn=[NSURLConnection connectionWithRequest:request delegate:self];
[conn start];

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    if (!_dataReceived) {
        _dataReceived=[[NSMutableData alloc]initWithData:data];
    }else{
        [_dataReceived appendData:data];
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    id result=[NSJSONSerialization JSONObjectWithData:_dataReceived options:kNilOptions error:nil];
    //result will be the parent object of the json what ever you are returning from json. may be array or dictionary.
}

我已经检查了您的网址。它返回的字典数组。结果将是数组。使用它。

【讨论】:

    猜你喜欢
    • 2017-12-17
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 2019-10-25
    • 2012-12-15
    • 2020-02-19
    • 2015-11-21
    相关资源
    最近更新 更多