1

如何使用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 框架来处理。

提前谢谢

4

2 回答 2

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];

但我建议使用块来代替异步调用!

于 2012-08-29T13:57:30.607 回答
0

要使用 RestKit 发出同步请求,请在正常设置实例后使用RKRequest'方法。-sendSynchronouslyRKRequest

于 2012-08-28T07:40:54.110 回答