如何在RestKit中发出同步请求?

时间:2012-08-28 06:44:04

标签: objective-c ios restkit

如何使用RestKit制作同步请求?

我之前用过这种方式(SBJSON):

UIDevice *myDevice = [UIDevice currentDevice];

    NSString *deviceUDID = [myDevice uniqueIdentifier];

    double v = [[[UIDevice currentDevice] systemVersion]doubleValue]; 
    NSString *version=[NSString stringWithFormat:@"%@ %.1f",deviceType,v];
    NSString *encodedParam1 =[version stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSString *requestString = [NSString stringWithFormat:@"method=views.get&view_name=client_list",nil];

    NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];

    NSString *urlString = [NSString stringWithFormat:@"http://localhost/index.php?oper=StoreDeviceId&device_id=%@&device_version=%@",deviceUDID,encodedParam1];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];

    [request setHTTPMethod: @"POST"];

    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    [request setHTTPBody: requestData];

    //Data returned by WebService

    NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];

    [request release];

    NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];

    NSDictionary *dict1 = [returnString JSONValue]; 

如何处理使用restkit框架的相同操作。

提前谢谢

2 个答案:

答案 0 :(得分:1)

以下是使用RKClient

的同步帖子的示例
//Configure RKLog
RKLogConfigureByName("RestKit/Network", RKLogLevelTrace);

//Set Client
RKClient *client = [RKClient clientWithBaseURLString:@"some_base_url"];

//Params to be send
NSDictionary *queryParameters = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"first_value",@"2",@"second_value",nil];

//Prepare the request and send it
RKRequest *request = [client post:@"path" params:queryParameters delegate:nil];
RKResponse *response = [request sendSynchronously];

//Process the response
NSString *stringResponse = [[NSString alloc] initWithData:[response body] encoding: NSUTF8StringEncoding];
NSDictionary *dict1 = [stringResponse JSONValue];

但我建议使用使用块的异步调用!。

答案 1 :(得分:0)

要使用RestKit发出同步请求,请在正常设置RKRequest实例后使用-sendSynchronously的{​​{1}}方法。