2012-03-22 5 views
1

json/rest api를 통해 서버에서 sqlite 데이터베이스를 검색하는 iPhone 응용 프로그램에서 작업하고 있습니다. 또한 사용자는 테이블에 로컬로 행을 추가하고 로컬로 업데이트 할 수 있습니다. 이제 로컬 데이터베이스의 테이블에 일부 행을 추가 했으므로 로컬 업데이트 된 데이터베이스에서 서버 데이터베이스에 새 행만 동기화/삽입하고 싶습니다. 누군가가 그 API 방법 (json/rest)에 대해 알고 있거나 도움이되는 튜토리얼이 있다면 도움을주십시오.json api를 통해 서버 db의 데이터를 업데이트하는 방법은 무엇입니까?

답변

3

"sqlite"데이터베이스를 검색하는 경우 모든 테이블과 행의 "json"표현을 의미합니까? 나는 당신이 실제로 "sqlite"db 파일을 보내지 않는다고 가정하고 있습니다.

HTTP를 통해 json을 보내고 가져 오는 데는 NSURLConnection과 NSURLRequest를 사용할 수 있습니다. 기본 데이터에 매핑하기를 원할 경우 연결 및 데이터 처리 모두에 RestKit 프레임 워크를 사용할 수 있습니다 .

이전 솔루션의 구현 예입니다. 사용자가 ARC라고 가정하고, 그렇지 않으면 적절한 retain 및 release 문을 추가해야합니다.

1) 적절한 위임

@interface ClassName : NSObject <NSURLConnectionDelegate> 

2) 데이터

//interface 
    @property (nonatomic, strong) NSMutableData *responseData;  

    //implementation 
    @synthesize responseData; 

3

을 수신하는 데 사용됩니다 드 responseData 오브젝트) 기능을 만들 선언으로 사용하고있는 클래스를 선언하는 json 요청을 보냅니다.

- (void)sendRequest 
{ 
    responseData = [NSMutableData data]; 

    //whatever your server address is 
    NSURL *url = [NSURL URLWithString:@"http://www.resturl.com/whatever"]; 

    //just sample data - create this dictionary with what you want to send 
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init]; 
    [params setObject:@"SomeValue" forKey:@"SomeKey"]; 


    NSError *jsonError; 
    //NSJSONSerialization is Apple's new json serialization class so we can use it to convert to and from json and foundation objects 
    NSData *requestdata = [NSJSONSerialization dataWithJSONObject:params options:0 error:&jsonError]; 

    NSMutableURLRequest *request; 
    request = [NSMutableURLRequest requestWithURL:url]; 
    [request setHTTPMethod:@"POST"]; 
    [request setValue:[NSString stringWithFormat:@"%d", [requestdata length]] forHTTPHeaderField:@"Content-Length"]; 
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
    [request setHTTPBody:requestdata]; 

    //this kicks off the request asynchronously 
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

    //if you'd rather send a synchronous request, you can use the static NSURLConnection function 
    //sendSynchronousRequest:returningResponse:error: 
} 

4) 수신하는 대리인 기능을 구현합니다. 우리의 데이터

//any time a piece of data is received we will append it to the responseData object 
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
    { 
     [self.responseData appendData:data]; 
    } 

    //some sort of error, you can print the error or put in some other handling here, possibly even try again but you will risk an infinite loop then unless you impose some sort of limit 
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
    { 
     // Clear the activeDownload property to allow later attempts 
     self.responseData = nil; 

    } 

    //connection has finished, thse requestData object should contain the entirety of the response at this point 
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection 
    { 
     NSError *jsonError; 
     NSDictionary *responseDict = 
     [NSJSONSerialization JSONObjectWithData:responseData 
             options:NSJSONWritingPrettyPrinted 
              error:&jsonError]; 
     if(responseDict) 
     { 
      NSLog(@"%@", responseDict); 
     } 
     else 
     { 
      NSLog(@"%@", [jsonError description]); 
     } 

     //clear out our response buffer for future requests 
     self.responseData = nil; 
    } 

당신은 몇 가지 새로운 정보를 원격 데이터베이스를 업데이트 단지 로컬 (보다는 전체 데이터 세트로 병합) 새로운 행을 추적하고 만 행을 포함하는 새로운 요청을 보내려면

추가 할 엔드 포인트에 연결하십시오. 이것이 실제 매핑을 시행하지 않고도이를 수행 할 수있는 가장 간단한 방법입니다.

관련 문제