使用场景,通常用在读不变的数据的plist文件,如地名,城市
需求
1、用plist文件初始化一个数组,并输出数组中的元素。
2、分别用同步和异步从网上下载图片存到本地。使用异步的时候,显示下载进度。
#import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate,NSURLConnectionDataDelegate> { long long totalLenth; long long receivedLenth; NSMutableData *mData; } @property (strong, nonatomic) UIWindow *window; @end
#import "AppDelegate.h" #define PATH1 @"http://h.hiphotos.baidu.com/image/w%3D2048/sign=4e4661fb3bdbb6fd255be2263d1caa18/42a98226cffc1e17951e59314890f603738de909.jpg" @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. self.window.backgroundColor = [UIColor whiteColor]; //1关键-路径 NSString *path = [[NSBundle mainBundle]pathForResource:@"abc" ofType:@"plist"]; NSArray *arr = [NSArray arrayWithContentsOfFile:path]; NSLog(@"arr = %@",arr); NSString *path2 = [[NSBundle mainBundle]pathForResource:@"Dictionary" ofType:@"plist"]; NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path2]; NSLog(@"dict = %@",dict); //2 NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:PATH1] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120.0f]; [NSURLConnection connectionWithRequest:req delegate:self]; [self.window makeKeyAndVisible]; return YES; } -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { mData = [[NSMutableData alloc]initWithLength:0];//不是0的话,里面参杂一些数据,会有问题 totalLenth = [response expectedContentLength];// } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [mData appendData:data]; receivedLenth = mData.length; float progress = receivedLenth * 100.0 / totalLenth;//低精靠向高精 NSLog(@"%lf%%",progress); } -(void)connectionDidFinishLoading:(NSURLConnection *)connection {
//NSLog(@"content = %@",[[NSString alloc]initWithData:mData encoding:NSUTF8StringEncoding]);图片不能转换成字符串,所以读出来为空,文本可以读取值 [mData writeToFile:@"/Users/yf02/Desktop/Oc_12/123.png" atomically:YES]; } -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { }
plist文件配置参考:http://blog.csdn.net/totogo2010/article/details/7634185