2012-02-08 29 views
5

Sto usando RestKit per la prima volta, e il suo set di funzionalità sembra fantastico. Ho letto il documento più volte ora e sto cercando di trovare un modo per parametrizzare JSON POST su un feed e mappare la risposta JSON. Dalla ricerca su StackOverflow ho trovato un modo per inviare i parametri JSON tramite GET, ma il mio server accetta solo POST.Come usare Restkit per POST JSON e risposta della mappa

Ecco il codice che ho finora:

RKObjectMapping *issueMapping = [RKObjectMapping mappingForClass:[CDIssue class]]; 
[objectMapping mapKeyPath:@"issue_id" toAttribute:@"issueId"]; 
[objectMapping mapKeyPath:@"title" toAttribute:@"issueTitle"]; 
[objectMapping mapKeyPath:@"description" toAttribute:@"issueDescription"]; 
RKObjectManager* manager = [RKObjectManager objectManagerWithBaseURL:@"http://restkit.org"]; 
RKManagedObjectStore* objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:@"News.sqlite"]; 
objectManager.objectStore = objectStore; 

NSDictionary params = [NSDictionary dictionaryWithObjectsAndKeys: @"myUsername", @"username", @"myPassword", @"password", nil]; 
NSURL *someURL = [objectManager.client URLForResourcePath:@"/feed/getIssues.json" queryParams:params]; 

[manager loadObjectsAtResourcePath:[someURL absoluteString] objectMapping:objectMapping delegate:self] 

dal thread un'altra StackOverflow (http://stackoverflow.com/questions/9102262/do-a-simple-json-post-using- restkit), io so come fare una semplice richiesta POST con il seguente codice:

RKClient *myClient = [RKClient sharedClient]; 
NSMutableDictionary *rpcData = [[NSMutableDictionary alloc] init ]; 
NSMutableDictionary *params = [[NSMutableDictionary alloc] init]; 

//User and password params 
[params setObject:password forKey:@"password"]; 
[params setObject:username forKey:@"email"]; 

//The server ask me for this format, so I set it here: 
[rpcData setObject:@"2.0" forKey:@"jsonrpc"]; 
[rpcData setObject:@"authenticate" forKey:@"method"]; 
[rpcData setObject:@"" forKey:@"id"]; 
[rpcData setObject:params forKey:@"params"]; 

//Parsing rpcData to JSON! 
id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:RKMIMETypeJSON]; 
NSError *error = nil; 
NSString *json = [parser stringFromObject:rpcData error:&error];  

//If no error we send the post, voila! 
if (!error){ 
    [[myClient post:@"/" params:[RKRequestSerialization serializationWithData:[json dataUsingEncoding:NSUTF8StringEncoding] MIMEType:RKMIMETypeJSON] delegate:self] send]; 
} 

Speravo che qualcuno mi avrebbe aiutato a sposare questi due frammenti di codice in una soluzione praticabile.

+0

Controlla questa domanda, questo dovrebbe aiutarti. http://stackoverflow.com/questions/9102262/do-a-simple-json-post-using-restkit – clopez

risposta

1

Per pubblicare un oggetto, quello che faccio è associare un percorso a un oggetto . Quindi utilizzare il metodo postObject da RKObjectManager.

Suppongo di aver già configurato RestKit in modo da avere il percorso di base impostato e definito la mappatura dell'oggetto per il tuo CDIssue come nel codice che hai già. Con questo in mente prova questo codice:

//We tell RestKit to asociate a path with our CDIssue class 
RKObjectRouter *router = [[RKObjectRouter alloc] init]; 
[router routeClass:[CDIssue class] toResourcePath:@"/path/to/my/cdissue/" forMethod:RKRequestMethodPOST]; 
[RKObjectManager sharedManager].router = router; 

//We get the mapping for the object that you want, in this case CDIssue assuming you already set that in another place 
RKObjectMapping *mapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass:[CDIssue class]]; 

//Post the object using the ObjectMapping with blocks 
[[RKObjectManager sharedManager] postObject:myEntity usingBlock:^(RKObjectLoader *loader) { 

    loader.objectMapping = mapping; 
    loader.delegate = self; 

    loader.onDidLoadObject = ^(id object) { 
     NSLog(@"Got the object mapped"); 
     //Be Happy and do some stuff here 
    }; 

    loader.onDidFailWithError = ^(NSError * error){ 
     NSLog(@"Error on request"); 
    }; 

    loader.onDidFailLoadWithError = ^(NSError * error){ 
     NSLog(@"Error on load"); 
    }; 

    loader.onDidLoadResponse = ^(RKResponse *response) { 
     NSLog(@"Response did arrive"); 
     if([response statusCode]>299){ 
      //This is useful when you get an error. You can check what did the server returned 
      id parsedResponse = [KFHelper JSONObjectWithData:[response body]]; 
      NSLog(@"%@",parsedResponse); 
     } 

    }; 


}]; 
+0

Grazie per la risposta. Ho postato la domanda originale a febbraio e ho abbandonato RestKit dopo aver ricevuto alcuna risposta. Non riesco davvero a ricordare come usarlo ora, quindi non posso testare questa risposta. Il codice sembra diverso da quello che ricordo della documentazione del restkit, quindi mi chiedo se abbiano modificato o aggiornato la libreria. – elprl

Problemi correlati