2012-09-20 56 views
2

我搜索了谷歌搜索用於使用REST風格的Web服務的不同方法和庫。但是當我嘗試舊圖書館時,他們中的大多數人都已經過時或失敗了。這可能是由於一些已經停產並且與新SDK不兼容的事實。iOS的當前庫使用REST風格的Web服務

我已經嘗試過SBJSON,ASIHTTP,stig和jsonframework,但是他們中沒有一個似乎在工作。

在iOS中使用RESTful Web服務的當前庫有哪些?如果有人可以使用相同的庫鏈接到示例教程,這將會很有幫助。

回答

6

嘗試RestKit:http://restkit.org/

衆所周知,流行,消費XML以及JSON和核心數據的工作原理(響應NSManagedObjects映射),這使偉大的後端作爲本地緩存。

+0

是的,我找到了一個教程,今天就試一試。 –

+0

你有什麼好的教程嗎?我正在嘗試http://mobile.tutsplus.com/tutorials/iphone/restkit_ios-sdk/和http://www.raywenderlich.com/13097/intro-to-restkit-tutorial,但我似乎得到錯誤,並且無法編譯它 –

+0

我總是將文檔看作最好的教程。此外,一切都解釋和鏈接到github安裝指南:https://github.com/RestKit/RestKit – Lukasz

3

爲什麼不使用NSURLConnection之類的iOS API類? (的iOS5及以上學歷,我認爲)

你可以調用REST GET例如opperation這樣的:

NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url]; 
[req setHTTPMethod:GET]; 
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];//for https 

connection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES]; 

其中URL應該是指向你的休息服務操作URL的NSURL對象。並聲明相應的代理方法:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; 
    code = [httpResponse statusCode]; 

    NSLog(@"%@ %i",@"Response Status Code: ",code); 

    [data setLength:0]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d { 
    [self.data appendData:d]; 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 

    [[[UIAlertView alloc] initWithTitle:@"Error" 
           message:nil 
           delegate:nil 
         cancelButtonTitle:@"ok" 
         otherButtonTitles:nil] show]; 
    self.connection = nil; 
    self.data = nil; 
} 

連接,數據和代碼可能是您的實現類的局部變量。在這些變量中,您將存儲建立的連接,收到的JSON數據(或其他)和響應http代碼,如200,404。

最後,如果您計劃調用受保護的REST服務,請不要忘記包括身份驗證代理。

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { 

      //set the user and password loged in 
      NSString *username = @"username"; 
      NSString *password = @"password";       

      NSURLCredential *credential = [NSURLCredential credentialWithUser:username 
                    password:password 
                     persistence:NSURLCredentialPersistenceForSession]; 
      [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; 

     } 

希望這有助於!

+0

謝謝,不知道蘋果已經發布了他們自己的類用於使用RESTful web服務。無法在Google上找到任何信息。今天會試試:) –

0

使用內置的NSURLSessionNSJSONSerialization,然後使用Github的Mantle框架將JSON字典映射到您的自定義ObjC對象。