9月中旬,開始動手作個人畢業設計了,以前一直在糾結作啥,後來想一想,既然是作畢業設計,那就大膽地作點本身沒接觸過的東西吧。而後網上查找資料得知作天氣預報須要用到開放的API,並且要用那種如今還在維護的,並且又免費的(對於咱們學生黨來講,這個是挺好的)。天氣預報App的核心是從天氣API請求數據,請求獲得的通常是JSON數據(這個JSON數據以前都沒接觸過),而後把JSON數據解析,而後在視圖上顯示出來。總得來講,這裏應該涉及到「網絡請求」,「JSON解析」這兩個大塊吧,正好用來學習新的東西,而且練練手,因而就決定作個天氣預報的App了。html
#import <Mantle/Mantle.h> #import <MTLModel.h> @interface TSCondition : MTLModel<MTLJSONSerializing> @property (nonatomic, strong) NSString *cityName; // 城市名字 @property (nonatomic, strong) NSString *nowCond; // 當前天氣情況 @property (nonatomic, strong) NSString *nowTmp; // 當前溫度 @property (nonatomic, strong) NSString *winddir; // 風向 @property (nonatomic, strong) NSString *windsc; // 風力 @property (nonatomic, strong) NSString *date; // 日期 @property (nonatomic, strong) NSString *maxTmp; // 最高溫度 @property (nonatomic, strong) NSString *minTmp; // 最低溫度 @property (nonatomic, strong) NSString *weatherqlty; // 空氣質量 @end
三、在.m文件中實現類方法,實現JSON數據到模型的映射sql
+ (NSDictionary *)JSONKeyPathsByPropertyKey { return @{ @"cityName": @"basic.city", @"nowCond": @"now.cond.txt", @"nowTmp": @"now.tmp", @"winddir": @"now.wind.dir", @"windsc": @"now.wind.sc", @"date": @"basic.update.loc", @"maxTmp": @"daily_forecast.tmp.max", @"minTmp": @"daily_forecast.tmp.min", @"weatherqlty": @"aqi.city.qlty" }; }
四、固然要接受到JSON數據要調用下面的方法,而且傳入帶有你要的數據的字典json
//建立NSDictionary NSData *JSONData = ...//接口的響應數據 NSDictionary *JSONDict = [NSJSONSerialization JSONObjectWithData: JSONData options: 0 error: nil]; //使用MTLJSONSerialization建立模型對象 CATProfile *profile = [MTLJSONAdapter modelOfClass: CATProfile.class fromJSONDictionary: JSONDict error: NULL];
通過重複的練習,熟悉了用Mantle把JSON數據轉模型以後,我就開始搭建App的UI了數組
@property(nonatomic,strong) NSMutableArray *viewControllerArr; // 存放視圖的數組 @property(nonatomic,assign) NSInteger curPage ; // 記錄當前 @property(nonatomic,assign) NSInteger totalPages ; // 記錄總頁數 // ***翻頁方法 // 日後翻 -(UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController{ self.curPage = ((ViewController *)viewController).page; UIImage *bgImg = [self createImageWithColor:((ViewController *)viewController).view.backgroundColor]; [self.navigationController.navigationBar setBackgroundImage:bgImg forBarMetrics:UIBarMetricsDefault]; self.pageControl.currentPage = self.curPage; if (self.curPage < self.totalPages - 1 && self.curPage != self.totalPages) { return self.viewControllerArr[self.curPage + 1]; }else{ return nil; } } // 往前翻 -(UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController{ self.curPage = ((ViewController *)viewController).page; UIImage *bgImg = [self createImageWithColor:((ViewController *)viewController).view.backgroundColor]; [self.navigationController.navigationBar setBackgroundImage:bgImg forBarMetrics:UIBarMetricsDefault]; self.pageControl.currentPage = self.curPage; if (self.curPage > 0 && self.curPage != self.totalPages) { return self.viewControllerArr[self.curPage - 1]; }else{ return nil; } }
+ (NSInteger)networkStatus { Reachability *reachability = [Reachability reachabilityWithHostName:@"http://www.heweather.com"];//網址可改 return [reachability currentReachabilityStatus]; }
// 如下代碼用於加載以前所定義的數據模型,並鏈接到一個SQLite數據存儲中。 // 實際上任何採用Core Data的應用,如下代碼的內容都是相同的。 - (NSManagedObjectModel *)managedObjectModel { if (_managedObjectModel == nil) { NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"DataModel" ofType:@"momd"]; NSURL *modelURL = [NSURL fileURLWithPath:modelPath]; _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; } return _managedObjectModel; } - (NSString *)documentsDirectory { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths lastObject]; return documentsDirectory; } - (NSString *)dataStorePath { return [[self documentsDirectory] stringByAppendingPathComponent:@"DataStore.sqlite"]; } - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (_persistentStoreCoordinator == nil) { NSURL *storeURL = [NSURL fileURLWithPath:[self dataStorePath]]; _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel]; NSError *error; if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { NSLog(@"Error adding persistent store %@,%@",error,[error userInfo]); abort(); } } return _persistentStoreCoordinator; } -(NSManagedObjectContext *)managedObjectContext { if (_managedObjectContext == nil) { NSPersistentStoreCoordinator *coordinator = self.persistentStoreCoordinator; if (coordinator != nil) { _managedObjectContext = [[NSManagedObjectContext alloc] init]; [_managedObjectContext setPersistentStoreCoordinator:coordinator]; } } return _managedObjectContext; }
4.編寫保存數據和查詢數據的方法,並在程序須要的地方調用
能夠參考http://blog.csdn.net/q199109106q/article/details/8563438這篇博客入門網絡
// 在圖片上加水印 + (instancetype)imageWithImage:(UIImage *)image andViewController:(ViewController *)controller { // 開啓位圖上下文 UIGraphicsBeginImageContextWithOptions(image.size, NO, 0); [image drawAtPoint:CGPointZero]; // 設置文字的樣式 NSDictionary *CityDict = @{ NSFontAttributeName : [UIFont fontWithName:@"KaiTi_GB2312" size: 40], NSForegroundColorAttributeName : [UIColor whiteColor] }; NSDictionary *dict = @{ NSFontAttributeName : [UIFont fontWithName:@"KaiTi_GB2312" size: 25], NSForegroundColorAttributeName : [UIColor whiteColor] }; CGFloat cityX = image.size.width - image.size.width / 4; CGFloat cityY = image.size.height / 13; // 畫上城市名 [controller.cityName drawAtPoint:CGPointMake(cityX , cityY) withAttributes:CityDict]; CGFloat imgX = cityX + 80; CGFloat imgY = cityY - 20; CGFloat imgW = 80; // 畫上天氣圖片 UIImage *condImg = [UIImage stringWithWeather:controller.jsonDic[@"now"][@"cond"][@"txt"]]; [condImg drawInRect:CGRectMake(imgX, imgY, imgW , imgW)]; CGFloat tempX = cityX + 40; CGFloat tempY = cityY + 60; // 畫上溫度計 UIImage *shape = [UIImage imageNamed:@"Shape"]; [shape drawInRect:CGRectMake(tempX-20, tempY, 14, 22)]; // 畫上溫度和天氣狀況 NSString *tempAndCond = [NSString stringWithFormat:@"%@℃ %@",controller.jsonDic[@"now"][@"tmp"],controller.jsonDic[@"now"][@"cond"][@"txt"]]; [tempAndCond drawAtPoint:CGPointMake(tempX, tempY) withAttributes:dict]; // 畫上APP標記 NSString *ts = @"天\n時"; [ts drawInRect:CGRectMake(10, image.size.height - 80,40,80) withAttributes:dict]; // 得到新圖片 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); //關閉上下文 UIGraphicsEndImageContext(); return newImage; }
使用:翻到你想要顯示的城市天氣頁面,選擇照片或者拍攝,完了以後再相冊就能查看到生成的圖片
效果圖:
框架
// 保存 - (void)isRefrash:(UISwitch *)sender { // [NSUserDefaults standardUserDefaults]能夠直接操做偏好設置文件夾 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; // 自動幫咱們生成一個plist文件存放在偏好設置的文件夾 [defaults setBool:sender.on forKey:@"switchStatus"]; // 同步:把內存中的數據和沙盒同步 [defaults synchronize]; } // 在UISwitch加載時讀取狀態 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [self.refashSwitch setOn:[defaults boolForKey:@"switchStatus"]];