通过URL为iOS应用程序获取Wordpress JSON数据

时间:2015-03-02 06:34:03

标签: ios json wordpress rest feed

我目前正在使用以下代码从我的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;

}

它的工作方式与我想要的静态数据相似,但我需要它通过实时网址动态工作。我正在使用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;

}

有任何建议或意见吗?谢谢!

1 个答案:

答案 0 :(得分:0)

我认为这可以解决您的问题。采取变量

@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.
}

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