从一个url中获得文本信息

Posted by Elton's Blog on January 6, 2010

有时候你可能需要从一个url中获取一个文本文件中的信息。 下面的例子会从我的博客页面下载大量的html信息。

-(void) readFromURL{
	NSError *error;
	NSURL *url = [NSURL URLWithString:@"https://blog.prosight.me/"];
	NSString *content = [NSString stringWithContentsOfURL: url
                     encoding:NSUTF8StringEncoding
                     error:&error];
}

主要是应用NSString的类方法:

+ (id)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error

encoding可以为以下这些中的一种

enum {
   NSASCIIStringEncoding = 1,
   NSNEXTSTEPStringEncoding = 2,
   NSJapaneseEUCStringEncoding = 3,
   NSUTF8StringEncoding = 4,
   NSISOLatin1StringEncoding = 5,
   NSSymbolStringEncoding = 6,
   NSNonLossyASCIIStringEncoding = 7,
   NSShiftJISStringEncoding = 8,
   NSISOLatin2StringEncoding = 9,
   NSUnicodeStringEncoding = 10,
   NSWindowsCP1251StringEncoding = 11,
   NSWindowsCP1252StringEncoding = 12,
   NSWindowsCP1253StringEncoding = 13,
   NSWindowsCP1254StringEncoding = 14,
   NSWindowsCP1250StringEncoding = 15,
   NSISO2022JPStringEncoding = 21,
   NSMacOSRomanStringEncoding = 30,
   NSUTF16StringEncoding = NSUnicodeStringEncoding,
   NSUTF16BigEndianStringEncoding = 0x90000100,
   NSUTF16LittleEndianStringEncoding = 0x94000100,
   NSUTF32StringEncoding = 0x8c000100,
   NSUTF32BigEndianStringEncoding = 0x98000100,
   NSUTF32LittleEndianStringEncoding = 0x9c000100,
};