2011-01-31 73 views
0

如何獲取Internet上的文件內容?例如,我想讓NSString獲得一個來自http://news.tut.by/rss/index.rss的RSS源內容。我該怎麼做?我只想使用iOS SDK類:NSURLConnection,NSURLRequest等。 P.S.我看到這樣的類:如何獲取互聯網上的文件內容?

#import <Foundation/Foundation.h> 


@interface RssDownloader : NSObject { 
NSURLConnection * conn; 
NSMutableData * receivedData; 
} 

@property(nonatomic, retain) NSURLConnection * conn; 
@property(nonatomic, retain) NSMutableData * receivedData; 

- (void)downloadUrlContent : (NSURL *)url; 
@end 




@implementation RssDownloader 

@synthesize receivedData, conn; 

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
[receivedData release]; 
receivedData = nil; 
} 

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

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
[connection release]; 
[receivedData release]; 
} 

- (void) connectionDidFinishLoading:(NSURLConnection *)connection { 
[connection release]; 
[receivedData release]; 
} 

- (void) downloadUrlContent:(NSURL *)url { 
NSURLRequest * urlRequest = [[NSURLRequest alloc] initWithURL:url 
       cachePolicy:NSURLRequestUseProtocolCachePolicy 
        timeoutInterval:60.0]; 
conn = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES]; 
if (conn) { 
    receivedData = [[NSMutableData data] retain]; 
} 
} 

- (void)dealloc { 
[conn release]; 
[receivedData release]; 
} 
@end 

但它不起作用。

+1

定義 「但它不工作」 – KevinDTimm 2011-01-31 15:22:21

回答

2

直到連接完成加載之前,您正在正確地做所有事情。在你做任何事情之前,你會發布數據。在你的委託類上,創建一個NSString變量(你可能已經有了這個)。然後,裏面connectionDidFinishLoading,將其轉換爲字符串釋放之前:

if(receivedData != nil){ 
    NSString *content = [NSString stringWithUTF8String:[receivedData bytes]]; 
    [receivedData release]; 
} 

祝您好運!

+0

這改變了我可以」即使經過之前被調用t接收文件的內容。我這樣做http://pastie.org/1514999 – 2011-01-31 15:51:14

+0

您鏈接到的代碼只調用URL。你修改了`connectionDidFinishLoading`方法嗎? – MystikSpiral 2011-01-31 16:02:29

0

我使用的時候有一個問題:

if(receivedData != nil){ 
    NSString *content = [NSString stringWithUTF8String:[receivedData bytes]]; 
    [receivedData release]; 
} 

問題是從我以.json文件損壞的字符串。 我使用:

[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding] 

有一個快速的方式來讀取遠程文件:

NSString *file = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:<your url here>] encoding:NSUTF8StringEncoding error:nil]; 

它是一種快速模式,但你沒有對服務器響應的任何控制。

1

變化

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
    [receivedData release]; 
    receivedData = nil; 
} 

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
} 

只是因爲功能didReceiveResponse將connectionDidFinishLoading