How to get a content of file on the Internet?
How to get a content of file on the Internet? For example, I want to get to NSString a content of rss feed from http://news.tut.by/rss/index.rss . How can I do it? I want to use only iOS SDK classes: NSURLConnection, NSURLRequest etc. P.S. I saw such class:
#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];
}
}开发者_如何学C
- (void)dealloc {
[conn release];
[receivedData release];
}
@end
but it doesn't work.
You are doing everything correctly right up until the connection finishes loading. There you are releasing the data before you do anything with it. On your delegate class, create an NSString
variable (you probably already have this). Then, inside connectionDidFinishLoading
, convert it to a string before releasing it:
if(receivedData != nil){
NSString *content = [NSString stringWithUTF8String:[receivedData bytes]];
[receivedData release];
}
Good Luck!
change
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[receivedData release];
receivedData = nil;
}
to
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
}
just because the function didReceiveResponse will be called before connectionDidFinishLoading
I had a problem when using:
if(receivedData != nil){
NSString *content = [NSString stringWithUTF8String:[receivedData bytes]];
[receivedData release];
}
The problem was a corrupted string from my .json file. I'm using:
[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]
There are a quick mode to read a remote file:
NSString *file = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:<your url here>] encoding:NSUTF8StringEncoding error:nil];
It is a quick mode, but you don't have any control about server's response.
精彩评论