iOS 7最佳实践:一个天气App案例

本系列教程指导您使用Cocoapods等工具和技术,从零开始构建一个iOS7天气应用,涵盖纯代码布局、数据映射、ReactiveCocoa函数编程等内容,通过实际案例深入理解iOS开发的最佳实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自: sjpsega's Blog
iOS7最佳实践:一个天气App案例(一)
 
注:本文译自: raywenderlich ios-7-best-practices-part-1,去除了跟主题无关的寒暄部分。
 
在这个两部分的系列教程中,您将探索如何使用以下工具和技术来创建自己的App:
Manual layout in code(纯代码布局)
 
本教程专为熟悉基本知识的、但还没有接触到太多高级主题的中级开发者而设计。本教程也是想要去探索Objective-C 函数编程一个很好的开始。
开始
打开Xcode并执行File\New\Project。选择Application\Empty Application。将项目命名为SimpleWeather,单击下一步,选择一个目录去保存你的项目,然后点击Create。 现在,你的基础项目已经完成。下一步是集成你的第三方工具。但首先你要关闭Xcode,确保他不会影响下一步。
 
Cocoapods
你将要下载 Cocoapods的代码,在Xcode项目中添加文件来使用,并配置项目需要的设置。
 
Mantle
Mantle是由于Github团队开发的,目的是去除Objective-C把JSON数据转为NSObject子类的所有样板代码。Mantle也能做数据转换,通过一种神奇的方式把JSON原始数据(strings, ints, floats)转换为复杂数据,比如NSDate, NSURL, 甚至是自定义类。
 
LBBlurredImage
LBBlurredImage是一个继承自UIImageView,轻而易举使图像模糊的项目。你将仅仅用一行代码来创建一个神奇的模糊效果。
 
TSMessages
TSMessages 是另一个非常简单的库,用来显示浮层警告和通知。当出现错误信息而不直接影响用户的时候,最好使用浮层来代替模态窗口(例如UIAlertView),这样你将尽可能减少对用户的影响。
 
你将只用TSMessages,在网络失去连接或API错误的时候。如果发生错误,你将看到类似这样的一个浮层:
ReactiveCocoa
最后,你将使用到 ReactiveCocoa,他也来自于GitHub团队。ReactiveCocoa给Objective-C带来了函数编程,类似与.NET的 Reactive Extensions。你将在第二部分花费大部分时间去实现ReactiveCocoa。
 
设置你的Cocoapods
 
设置你的Cocoapods,先要确保你已经安装了Cocoapods。为此,打开命令行程序,并输入。
 
 
  1. which pod 
 
你将会看到类似这样的输出:
 
 
  1. /usr/bin/pod 
这决定于你如何管理Ruby gems,例如你使用 rbenvRVM,路径可能有所不同。
 
如果命令行简单的返回提示,或显示pod not found,表示Cocoapods未安装在你的机器上。可以查看我们的 Cocoapods教程作为安装说明。这也是一个很好的资源,如果你想更多得了解Cocoapods的话。
 
Podfiles是用来告诉Cocoapods哪些开源项目需要导入。
 
要创建你的第一个Cocoapod,首先在命令行中用cd命令导航到你的XCode项目所在的文件夹,在命令行中启动编辑器,输入
 
 
  1. platform :ios, '7.0' 
  2.   
  3. pod 'Mantle' 
  4. pod 'LBBlurredImage' 
  5. pod 'TSMessages' 
  6. pod 'ReactiveCocoa' 
这文件做了两件事情:
1.告诉Cocoapods你的目标平台与版本,这里的你目标是iOS 7.0。
2.列给Cocoapods一个项目所有需要引入和安装的三方库清单。
 
在命令行中输入pod install进行安装。
 
这可能需要花一到两分钟的时间去安装各种包。你的命令行应该输出如下所示:
 
 
  1. $ pod install 
  2. Analyzing dependencies 
  3.   
  4. CocoaPods 0.28.0 is available. 
  5.   
  6. Downloading dependencies 
  7. Installing HexColors (2.2.1) 
  8. Installing LBBlurredImage (0.1.0) 
  9. Installing Mantle (1.3.1) 
  10.   
  11. Installing ReactiveCocoa (2.1.7) 
  12. Installing TSMessages (0.9.4) 
  13. Generating Pods project 
  14. Integrating client project 
  15.   
  16. [!] From now on use `SimpleWeather.xcworkspace`. 
 
 
 
  1. sjpsega注:若你之前安装过Cocoapods的话,这里安装报错的话,可以看看http://blog.cocoapods.org/Repairing-Our-Broken-Specs-Repository/ 修复问题 
Cocoapods会在你的项目目录中创建一堆新文件,但是,只有一个需要你关心,SimpleWeather.xcworkspace。
 
用Xcode打开SimpleWeather.xcworkspace。看看你的项目设置,现在有一个Pods项目在你的项目工作区,以及在Pods文件夹放着每一个你引入的库,如下所示:
确保你已经选择SimpleWeather项目,如图所示: Select SimpleWeather Project
构建并运行您的App,以确保一切工作正常: 
 
 
  1. 提示:您可能会注意到有一些项目生成警告。因为Cocoapods引入的项目,是由不同的开发者开发,并且不同的开发者对生成警告有不同的态度。通常,你应该可以忽略它们。只要确保没有任何编译器错误! 
 
创建你的主视图控制器
 
虽然这个App看起来复杂,但它还会通过一个单一的View Controller完成。现在,你将添加他。
 
选中SimpleWeather项目,单击File\New\File,并且选择Cocoa Touch\Objective-C class. 命名为WXController,并设置为UIViewController的子类。
 
确保Targeted for iPad和With XIB for user interface都没有选中,如下图所示: Create WXController
 
打开WXController.m然后用如下所示替换-viewDidLoad方法:
 
 
  1. - (void)viewDidLoad { 
  2.     [super viewDidLoad]; 
  3.  
  4.     // Remove this later 
  5.     self.view.backgroundColor = [UIColor redColor]; 
 
现在打开AppDelegate.m,并且引入如下两个class:
 
 
  1. #import "WXController.h" 
  2. #import <TSMessage.h> 
眼尖的读者会注意到WXController使用引号引入,TSMessage使用单括号引入。
 
回头看下当你创建Podfile的时候,你使用Cocoapods引入TSMessage。Cocoapods创建TSMessage项目,并把它加入到工作空间。既然你从工作区的其他项目导入,可以使用尖括号代替引号。
 
代替-application:didFinishLaunchingWithOptions的内容:
 
 
  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 
  2.     self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 
  3.     // 1 
  4.     self.window.rootViewController = [[WXController alloc] init]; 
  5.     self.window.backgroundColor = [UIColor whiteColor]; 
  6.     [self.window makeKeyAndVisible]; 
  7.     // 2 
  8.     [TSMessage setDefaultViewController: self.window.rootViewController]; 
  9.     return YES; 
标号注释的解释:
1.初始化并设置WXController实例作为App的根视图控制器。通常这个控制器是一个的UINavigationController或UITabBarController,但在当前情况下,你使用WXController的单个实例。
2.设置默认的视图控制器来显示你的TSMessages。这样做,你将不再需要手动指定要使用的控制器来显示警告。
 
构建并运行,看看你的新视图控制器起作用了。
 
 
在红色背景下,状态栏有点不够清晰。幸运的是,有一个简单的方法,使状态栏更清晰易读。
 
在iOS7, UIViewController有一个新的API,用来控制状态栏的外观。打开WXController,直接添加下面的代码到-viewDidLoad:方法下:
 
 
  1. - (UIStatusBarStyle)preferredStatusBarStyle { 
  2.     return UIStatusBarStyleLightContent; 
再次构建并运行,你将看到状态栏如下的变化:
设置你的App视图
 
现在是时候让你的App接近生活。下载这个项目的 图片,并解压缩到一个合适的位置。这个压缩包的背景图片出自Flickr用户 idleformat之手,天气图片出自Dribbble用户 heeyeun之手。
 
切换回Xcode,单击File\Add Files to “SimpleWeather”….定位到你刚刚解压缩的图片文件夹并选择它。选择Copy items into destination group’s folder (if needed),然后单击Add。
 
打开WXController.h, 添加如下委托协议:
 
 
  1. <UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate> 
现在打开WXController.m。 小提示:你可以使用Control-Command-Up的快捷键来实现.h和.m文件之间的快速切换。
 
添加如下代码到WXController.m顶部:
 
 
  1. #import <LBBlurredImage/UIImageView+LBBlurredImage.h> 
LBBlurredImage.h包含在Cocoapods引入的LBBlurredImage项目,你会使用这个库来模糊背景图片。
 
应该有一个空的私有接口样板在WXController imports的下方。它具有以下属性:
 
 
  1. @interface WXController () 
  2.  
  3. @property (nonatomic, strong) UIImageView *backgroundImageView; 
  4. @property (nonatomic, strong) UIImageView *blurredImageView; 
  5. @property (nonatomic, strong) UITableView *tableView; 
  6. @property (nonatomic, assign) CGFloat screenHeight; 
  7.  
  8. @end 
现在,是时候在项目中创建并设置视图。
 
下面是你App的分解图,记住,table view将是透明的:
 
为了实现动态模糊效果,在你的App中,你会根据App的滚动来改变模糊图像的alpha值。
 
打开WXController.m,使用如下代码来,替换掉-viewDidLoad中设置背景色的代码:
 
 
  1. // 1 
  2. self.screenHeight = [UIScreen mainScreen].bounds.size.height; 
  3.  
  4. UIImage *background = [UIImage imageNamed:@"bg"]; 
  5.  
  6. // 2 
  7. self.backgroundImageView = [[UIImageView alloc] initWithImage:background]; 
  8. self.backgroundImageView.contentMode = UIViewContentModeScaleAspectFill; 
  9. [self.view addSubview:self.backgroundImageView]; 
  10.  
  11. // 3 
  12. self.blurredImageView = [[UIImageView alloc] init]; 
  13. self.blurredImageView.contentMode = UIViewContentModeScaleAspectFill; 
  14. self.blurredImageView.alpha = 0; 
  15. [self.blurredImageView setImageToBlur:background blurRadius:10 completionBlock:nil]; 
  16. [self.view addSubview:self.blurredImageView]; 
  17.  
  18. // 4 
  19. self.tableView = [[UITableView alloc] init]; 
  20. self.tableView.backgroundColor = [UIColor clearColor]; 
  21. self.tableView.delegate = self; 
  22. self.tableView.dataSource = self; 
  23. self.tableView.separatorColor = [UIColor colorWithWhite:1 alpha:0.2]; 
  24. self.tableView.pagingEnabled = YES; 
  25. [self.view addSubview:self.tableView]; 
这是非常简单的代码:
1.获取并存储屏幕高度。之后,你将在用分页的方式来显示所有天气??数据时,使用它。
2.创建一个静态的背景图,并添加到视图上。
3.使用LBBlurredImage来创建一个模糊的背景图像,并设置alpha为0,使得开始backgroundImageView是可见的。
4.创建tableview来处理所有的数据呈现。 设置WXController为delegate和dataSource,以及滚动视图的delegate。请注意,设置pagingEnabled为YES。
 
添加如下UITableView的delegate和dataSource的代码到WXController.m的@implementation块中:
 
 
  1. // 1 
  2. #pragma mark - UITableViewDataSource 
  3.  
  4. // 2 
  5. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
  6.     return 2; 
  7.  
  8. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
  9.     // TODO: Return count of forecast 
  10.     return 0; 
  11.  
  12. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
  13.     static NSString *CellIdentifier = @"CellIdentifier"
  14.     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
  15.  
  16.     if (! cell) { 
  17.         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier]; 
  18.     } 
  19.  
  20.     // 3 
  21.     cell.selectionStyle = UITableViewCellSelectionStyleNone; 
  22.     cell.backgroundColor = [UIColor colorWithWhite:0 alpha:0.2]; 
  23.     cell.textLabel.textColor = [UIColor whiteColor]; 
  24.     cell.detailTextLabel.textColor = [UIColor whiteColor]; 
  25.  
  26.     // TODO: Setup the cell 
  27.  
  28.     return cell; 
  29.  
  30. #pragma mark - UITableViewDelegate 
  31.  
  32. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
  33.     // TODO: Determine cell height based on screen 
  34.     return 44; 
Pragma mark是 组织代码的很好的一种方式。
 
你的table view有两个部分,一个是每小时的天气预报,另一个用于每日播报。table view的section数目,设置为2。
 
天气预报的cell是不可选择的。给他们一个半透明的黑色背景和白色文字。
 
 
  1. 注意:使用格式化的注释 // TODO:可以帮助Xcode找到需要以后完成的代码。你还可以使用 Show Document Items(Control-6)来查看TODO项。 
最后,添加如下代码到WXController.m:
 
 
  1. - (void)viewWillLayoutSubviews { 
  2.     [super viewWillLayoutSubviews]; 
  3.  
  4.     CGRect bounds = self.view.bounds; 
  5.  
  6.     self.backgroundImageView.frame = bounds; 
  7.     self.blurredImageView.frame = bounds; 
  8.     self.tableView.frame = bounds; 
 
在WXController.m中,你的视图控制器调用该方法来编排其子视图。
 
构建并运行你的App,看看你的视图如何堆叠。
 
 
仔细看,你会看到所有空的table cell的cell分隔线。
 
仍然在-viewDidLoad中,添加下面的代码来设置你的布局框架和边距:
 
 
  1. // 1 
  2. CGRect headerFrame = [UIScreen mainScreen].bounds; 
  3. // 2 
  4. CGFloat inset = 20; 
  5. // 3 
  6. CGFloat temperatureHeight = 110; 
  7. CGFloat hiloHeight = 40; 
  8. CGFloat iconHeight = 30; 
  9. // 4 
  10. CGRect hiloFrame = CGRectMake(inset, 
  11.                               headerFrame.size.height - hiloHeight, 
  12.                               headerFrame.size.width - (2 * inset), 
  13.                               hiloHeight); 
  14.  
  15. CGRect temperatureFrame = CGRectMake(inset, 
  16.                                      headerFrame.size.height - (temperatureHeight + hiloHeight), 
  17.                                      headerFrame.size.width - (2 * inset), 
  18.                                      temperatureHeight); 
  19.  
  20. CGRect iconFrame = CGRectMake(inset, 
  21.                               temperatureFrame.origin.y - iconHeight, 
  22.                               iconHeight, 
  23.                               iconHeight); 
  24. // 5 
  25. CGRect conditionsFrame = iconFrame; 
  26. conditionsFrame.size.width = self.view.bounds.size.width - (((2 * inset) + iconHeight) + 10); 
  27. conditionsFrame.origin.x = iconFrame.origin.x + (iconHeight + 10); 
 
这是相当常规设置代码,但这里是怎么回事:
1.设置table的header大小与屏幕相同。你将利用的UITableView的分页来分隔页面页头和每日每时的天气预报部分。
2.创建inset(或padding)变量,以便您的所有标签均匀分布并居中。
3.创建并初始化为各种视图创建的高度变量。设置这些值作为常量,使得可以很容易地在需要的时候,配置和更改您的视图设置。
4.使用常量和inset变量,为label和view创建框架。
5.复制图标框,调整它,使文本具有一定的扩展空间,并将其移动到该图标的右侧。当我们把标签添加到视图,你会看到布局的效果。
 
添加如下代码到-viewDidLoad:
 
 
  1. // 1 
  2. UIView *header = [[UIView alloc] initWithFrame:headerFrame]; 
  3. header.backgroundColor = [UIColor clearColor]; 
  4. self.tableView.tableHeaderView = header; 
  5.  
  6. // 2 
  7. // bottom left 
  8. UILabel *temperatureLabel = [[UILabel alloc] initWithFrame:temperatureFrame]; 
  9. temperatureLabel.backgroundColor = [UIColor clearColor]; 
  10. temperatureLabel.textColor = [UIColor whiteColor]; 
  11. temperatureLabel.text = @"0°"
  12. temperatureLabel.font = [UIFont fontWithName:@"HelveticaNeue-UltraLight" size:120]; 
  13. [header addSubview:temperatureLabel]; 
  14.  
  15. // bottom left 
  16. UILabel *hiloLabel = [[UILabel alloc] initWithFrame:hiloFrame]; 
  17. hiloLabel.backgroundColor = [UIColor clearColor]; 
  18. hiloLabel.textColor = [UIColor whiteColor]; 
  19. hiloLabel.text = @"0° / 0°"
  20. hiloLabel.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:28]; 
  21. [header addSubview:hiloLabel]; 
  22.  
  23. // top 
  24. UILabel *cityLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, 30)]; 
  25. cityLabel.backgroundColor = [UIColor clearColor]; 
  26. cityLabel.textColor = [UIColor whiteColor]; 
  27. cityLabel.text = @"Loading..."
  28. cityLabel.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:18]; 
  29. cityLabel.textAlignment = NSTextAlignmentCenter; 
  30. [header addSubview:cityLabel]; 
  31.  
  32. UILabel *conditionsLabel = [[UILabel alloc] initWithFrame:conditionsFrame]; 
  33. conditionsLabel.backgroundColor = [UIColor clearColor]; 
  34. conditionsLabel.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:18]; 
  35. conditionsLabel.textColor = [UIColor whiteColor]; 
  36. [header addSubview:conditionsLabel]; 
  37.  
  38. // 3 
  39. // bottom left 
  40. UIImageView *iconView = [[UIImageView alloc] initWithFrame:iconFrame]; 
  41. iconView.contentMode = UIViewContentModeScaleAspectFit; 
  42. iconView.backgroundColor = [UIColor clearColor]; 
  43. [header addSubview:iconView]; 
 
这是相当长的一块代码,但它真的只是在做设置各种控件的繁重工作。简单的说:
1.设置当前view为你的table header。
2.构建每一个显示气象数据的标签。
3.添加一个天气图标的图像视图。
 
构建并运行你的App,你应该可以看到你之前布局的所有所有view。下面的屏幕截图显示了使用手工布局的、所有标签框在视觉上的显示。
用手指轻轻推动table,当你滚动它的时候,应该会反弹。
 
获取气象数据
你会注意到,App显示“Loading…”,但它不是真正地在工作。是时候获取一些真正的天气数据。
 
你会从 OpenWeatherMap的API拉取数据。 OpenWeatherMap是一个非常棒的服务,旨在提供实时,准确,免费的天气数据给任何人。虽然有很多天气API,但他们大多要么使用较旧的数据格式,如XML,或是有偿服务 – 并且有时还相当昂贵。
 
你会遵循以下基本步骤,来获你设备的位置的气象数据:
1.找到设备的位置
2.从 API端下载JSON数据
3.映射JSON到WXConditions和WXDailyForecasts
4.告诉UI有新数据了
开始创建你的天气模型和数据管理类。单击File\New\File…并选择Cocoa Touch\Objective-C class。命名为WXClient并使其为NSObject的子类。
 
这样再做三次创建以下类:
1.WXManager作为NSObject的子类
2.WXCondition作为MTLModel的子类
3.WXDailyForecast作为WXCondition的子类
 
全部完成?现在,你可以开始下一节,其中涉及映射和转换您的天气数据。
 
创建你的天气模型
你的模型将使用 Mantle,这使得数据映射和转型非常简单。
 
打开WXCondition.h如下列代码,修改接口:
 
 
  1. // 1 
  2. @interface WXCondition : MTLModel <MTLJSONSerializing> 
  3.  
  4. // 2 
  5. @property (nonatomic, strong) NSDate *date; 
  6. @property (nonatomic, strong) NSNumber *humidity; 
  7. @property (nonatomic, strong) NSNumber *temperature; 
  8. @property (nonatomic, strong) NSNumber *tempHigh; 
  9. @property (nonatomic, strong) NSNumber *tempLow; 
  10. @property (nonatomic, strong) NSString *locationName; 
  11. @property (nonatomic, strong) NSDate *sunrise; 
  12. @property (nonatomic, strong) NSDate *sunset; 
  13. @property (nonatomic, strong) NSString *conditionDescription; 
  14. @property (nonatomic, strong) NSString *condition; 
  15. @property (nonatomic, strong) NSNumber *windBearing; 
  16. @property (nonatomic, strong) NSNumber *windSpeed; 
  17. @property (nonatomic, strong) NSString *icon; 
  18.  
  19. // 3 
  20. - (NSString *)imageName; 
  21.  
  22. @end 
MTLJSONSerializing协议告诉Mantle序列化该对象如何从JSON映射到Objective-C的属性。
 
这些都是你的天气数据的属性。你将会使用这些属性的get set方法,但是当你要扩展App,这是一种很好的方法来访问数据。
 
这是一个简单的辅助方法,从天气状况映射到图像文件。
 
构建并运行App。失败了……
 
原因是你没有从你的Cocoapods项目中引入Mantle。解决方法是,在WXCondition.h中,你需要把MTLModel.h替换为#import <Mantle.h>。
 
现在构建并运行App。成功了。你会看到一些新的警告,但你可以忽略他们。
 
首先,你需要处理未实现的-imageName方法。
 
打开WXCondition.m,添加如下方法:
 
 
  1. + (NSDictionary *)imageMap { 
  2.     // 1 
  3.     static NSDictionary *_imageMap = nil; 
  4.     if (! _imageMap) { 
  5.         // 2 
  6.         _imageMap = @{ 
  7.                       @"01d" : @"weather-clear"
  8.                       @"02d" : @"weather-few"
  9.                       @"03d" : @"weather-few"
  10.                       @"04d" : @"weather-broken"
  11.                       @"09d" : @"weather-shower"
  12.                       @"10d" : @"weather-rain"
  13.                       @"11d" : @"weather-tstorm"
  14.                       @"13d" : @"weather-snow"
  15.                       @"50d" : @"weather-mist"
  16.                       @"01n" : @"weather-moon"
  17.                       @"02n" : @"weather-few-night"
  18.                       @"03n" : @"weather-few-night"
  19.                       @"04n" : @"weather-broken"
  20.                       @"09n" : @"weather-shower"
  21.                       @"10n" : @"weather-rain-night"
  22.                       @"11n" : @"weather-tstorm"
  23.                       @"13n" : @"weather-snow"
  24.                       @"50n" : @"weather-mist"
  25.                       }; 
  26.     } 
  27.     return _imageMap; 
  28.  
  29. // 3 
  30. - (NSString *)imageName { 
  31.     return [WXCondition imageMap][self.icon]; 
创建一个静态的NSDictionary,因为WXCondition的每个实例都将使用相同的数据映射。
 
天气状况与图像文件的关系(例如“01d”代表“weather-clear.png”)。
 
声明获取图像文件名的公有方法。
 
看一看从OpenWeatherMap返回的JSON响应数据:
 
 
  1.     "dt": 1384279857, 
  2.     "id": 5391959, 
  3.     "main": { 
  4.         "humidity": 69, 
  5.         "pressure": 1025, 
  6.         "temp": 62.29, 
  7.         "temp_max": 69.01, 
  8.         "temp_min": 57.2 
  9.     }, 
  10.     "name""San Francisco"
  11.     "weather": [ 
  12.         { 
  13.             "description""haze"
  14.             "icon""50d"
  15.             "id": 721, 
  16.             "main""Haze" 
  17.         } 
  18.     ] 
你需要把嵌套的JSON值映射到Objective-C的属性。嵌套的JSON值是元素,如温度,即上面看到的main节点。
 
要做到这一点,你将利用的Objective-C的 Key-Value Coding和Mantle的 MTLJSONAdapter
 
还在WXCondition.m,通过添加+JSONKeyPathsByPropertyKey方法,“JSON到模型属性”的映射,且该方法是MTLJSONSerializing协议的 require
 
 
  1. + (NSDictionary *)JSONKeyPathsByPropertyKey { 
  2.     return @{ 
  3.              @"date": @"dt"
  4.              @"locationName": @"name"
  5.              @"humidity": @"main.humidity"
  6.              @"temperature": @"main.temp"
  7.              @"tempHigh": @"main.temp_max"
  8.              @"tempLow": @"main.temp_min"
  9.              @"sunrise": @"sys.sunrise"
  10.              @"sunset": @"sys.sunset"
  11.              @"conditionDescription": @"weather.description"
  12.              @"condition": @"weather.main"
  13.              @"icon": @"weather.icon"
  14.              @"windBearing": @"wind.deg"
  15.              @"windSpeed": @"wind.speed" 
  16.              }; 
在这个方法里,dictionary的key是WXCondition的属性名称,而dictionary的value是JSON的路径。
 
您可能已经注意到,这里有一个从JSON数据映射到Objective-C属性的问题。属性date是NSDate类型的,但JSON有一个Unix时间类型(sjpsega注:即从1970年1月1日0时0分0秒起至现在的总秒数)的NSInteger值。你需要完成两者之间的转换。
 
Mantle正好有一个功能来为你解决这个问题: MTLValueTransformer。这个类允许你声明一个block,详细说明值的相互转换。
 
Mantle的转换器语法有点怪。要创建一个为一个特定属性的转换器,,您可以添加一个以属性名开头和JSONTransformer结尾的类方法。 可能看实际代码比试图解释它更容易理解,所以在WXCondition.m中添加以下为NSDate属性设置的转换器。
 
 
  1. + (NSValueTransformer *)dateJSONTransformer { 
  2.     // 1 
  3.     return [MTLValueTransformer reversibleTransformerWithForwardBlock:^(NSString *str) { 
  4.         return [NSDate dateWithTimeIntervalSince1970:str.floatValue]; 
  5.     } reverseBlock:^(NSDate *date) { 
  6.         return [NSString stringWithFormat:@"%f",[date timeIntervalSince1970]]; 
  7.     }]; 
  8.  
  9. // 2 
  10. + (NSValueTransformer *)sunriseJSONTransformer { 
  11.     return [self dateJSONTransformer]; 
  12.  
  13. + (NSValueTransformer *)sunsetJSONTransformer { 
  14.     return [self dateJSONTransformer]; 
使用blocks做属性的转换的工作,并返回一个MTLValueTransformer返回值。
 
您只需要详细说明Unix时间和NSDate之间进行转换一次,就可以重用-dateJSONTransformer方法为sunrise和sunset属性做转换。
 
下一个值转型有点讨厌,但它只是使用OpenWeatherMap的API,并自己的格式化JSON响应方式的结果。weather键对应的值是一个JSON数组,但你只关注单一的天气状况。
 
在WXCondition.m中,使用dateJSONTransformer相同的结构,您可以创建一个NSArray和NSString的之间的转换。该解决方案提供如下:
 
 
  1. + (NSValueTransformer *)conditionDescriptionJSONTransformer { 
  2.     return [MTLValueTransformer reversibleTransformerWithForwardBlock:^(NSArray *values) { 
  3.         return [values firstObject]; 
  4.     } reverseBlock:^(NSString *str) { 
  5.         return @[str]; 
  6.     }]; 
  7.  
  8. + (NSValueTransformer *)conditionJSONTransformer { 
  9.     return [self conditionDescriptionJSONTransformer]; 
  10.  
  11. + (NSValueTransformer *)iconJSONTransformer { 
  12.     return [self conditionDescriptionJSONTransformer]; 
最后的转换器只是为了格式化。 OpenWeatherAPI使用每秒/米的风速。由于您的App使用英制系统,你需要将其转换为每小时/英里。
 
在WXCondition.m的实现中添加以下转换器的方法和宏定义。
 
 
  1. #define MPS_TO_MPH 2.23694f 
  2.  
  3. + (NSValueTransformer *)windSpeedJSONTransformer { 
  4.     return [MTLValueTransformer reversibleTransformerWithForwardBlock:^(NSNumber *num) { 
  5.         return @(num.floatValue*MPS_TO_MPH); 
  6.     } reverseBlock:^(NSNumber *speed) { 
  7.         return @(speed.floatValue/MPS_TO_MPH); 
  8.     }]; 
 在OpenWeatherMap的API中有一个小的差异,你必须处理。看一看在位于 当前状况的响应和 每日预测反应之间的温度:
 
 
  1. // current 
  2. "main": { 
  3.     "grnd_level": 1021.87, 
  4.     "humidity": 64, 
  5.     "pressure": 1021.87, 
  6.     "sea_level": 1030.6, 
  7.     "temp": 58.09, 
  8.     "temp_max": 58.09, 
  9.     "temp_min": 58.09 
  10.  
  11. // daily forecast 
  12. "temp": { 
  13.     "day": 58.14, 
  14.     "eve": 58.14, 
  15.     "max": 58.14, 
  16.     "min": 57.18, 
  17.     "morn": 58.14, 
  18.     "night": 57.18 
current的第一个key是main,最高温度存储在key temp_max中,而daily forecast的第一个key是temp,最高温度存储在key max中。
 
key Temperature的差异放在一边,其他都一样。所以,你真正需要做的是修改daily forecasts的键映射。
 
打开WXDailyForecast.m重写+JSONKeyPathsByPropertyKey方法:
 
 
  1. + (NSDictionary *)JSONKeyPathsByPropertyKey { 
  2.     // 1 
  3.     NSMutableDictionary *paths = [[super JSONKeyPathsByPropertyKey] mutableCopy]; 
  4.     // 2 
  5.     paths[@"tempHigh"] = @"temp.max"
  6.     paths[@"tempLow"] = @"temp.min"
  7.     // 3 
  8.     return paths; 
获取WXCondition的映射,并创建它的可变副本。
 
你需要为daily forecast做的是改变max和min键映射。
 
返回新的映射。
 
构建并运行您的App,看起来和上次运行没什么改变,但好的一点是,App编译和运行没有任何错误。
 
 
何去何从?
 
你可以从这里 这里完整程序。
 
在这部分教程中,您使用Cocoapods设置项目,增加视图到控制器,编排视图,并建立模型来反映你抓取的气象数据。该App还没有充分发挥作用,但是你成功用纯代码创建视图,并学习了如何使用Mantle映射和转换JSON数据。
 
接下来看看教程的第二部分,你将充实你的App,从weather API获取数据,并在UI上显示。您将使用新的iOS7  NSURLSession去下载数据,以及使用ReactiveCocoa把位置查找,天气数据抓取和UI更新事件绑在一起。
 
iOS 7最佳实践:一个天气App案例
一、数据库的背景及功能需求 进入21世纪以来,计算机的普及应用和信息技术、网络技术的发展给人们的工作和生活带来了极大的便利和高效,信息化、电子化已经成为节约运营成本,提高工作效率的首选。 相比之下,国内的相当数量的中小型医院的病人资料工作流程还采用相对保守的人工工作方式,数据信息的查询和存储的成本较高,而且效率还很低下。所以需要一种对于医院的病人资料管理系统来高效、低成本、便捷的进行医院病人信息数据的查询和存储。 1. 病人的相关信息应该由医院数据库管理员进行添加、删除、修改、查询等维护操作。 2. 需通过病人所患的疾病来确定病人的治疗 3. 对病人的编号、出生日期、性别、工作、住址信息进行查询。 4. 对病人的治疗进程,缴费情况等进行及时的更新与统一管理。 5. 医院需通过治疗结果来查看病人是否结束治疗,以进行必要的及时续约等行为。 6. 病人可通过数据库进行对所交费用,治疗情况的相关信息进行查看。 7. 病人信息的更新等等由数据库管理员进行维护。 系统功能的基本功能: 1病人信息包含编号,姓名,性别,出生日期,工作单位及地址,住址,工作,保险,医保号,电话,邮箱,死亡日期。 2交费项目信息包含项目序号,项目类型,缴费金额等 3回访记录包含住号,病人编号,回访日期,回访人,记录,生命体征。 4 可通过对数据库的查询了解病人的相关信息,以及病情,并确定治疗方案。 所有关系模式都属于BC范式 (1)在关系模式patient中patientID是主键,所以在包含属性patientID的函数依赖是一个superkey。 (2)在关系模式中inpatient中number为主键,所以在所包含属性number的函数依赖是一个superkey。 (3)在关系模式outpatient中patientID为主键,所以包含patientID的函数依赖是一个superkey。 (4)在关系模式bed中number是主键,所以包含patientID的函数依赖是一个superkey。 (5)在关系模式department中depname是主键,所以在包含属性depname的函数依赖是一个superkey。 (6)在关系模式中re_call中number为主键,所以在所包含属性number的函数依赖是一个superkey。 (7)在关系模式case中caseID为主键,所以包含caseID的函数依赖是一个superkey。 (8)在关系模式charge1中chargeID是主键,所以包含chargeID的函数依赖是一个superkey。 (9)在关系模式charge2中chargeID是主键,所以在包含属性chargeID的函数依赖是一个superkey。 (10)在关系模式中inotice中inoticeID为主键,所以在所包含属性inoticeID的函数依赖是一个superkey。所以一定属于BCNF。 二、数据库的概念结构设计 病人资料管理系统的E-R模型 三、数据库的物理结构设计 住病人inpatient 列名 数据类型 字段长度 字段描述 备注 Number Bigint 住号 主键 patientID bigint 病人编号 非空,外码 Name Bigint 姓名 Inday Datetime 入时间 Bedroom char 4 床号 Sort varchar 20 入科别 病人信息表patient 列名 数据类型 长度 字段描述 备注 patientID bigint 病人编号 主键 Name varchar 20 姓名 不能为空 Sex char 4 性别 Birth datetime 出生日期 Dep varchar 40 单位 Depadd varchar 60 单位地址 address varchar 60 住址 Work varchar 10 工作 在职、离休、退休 Insure char 4 医保 insnumb varchar 30 医保号 有、无,不为空 Tel varchar 10 电话 Email varchar 50 E-mail deathday varchar 20 死亡日期 门病人表outpatient 列名 数据类型 字段长度 字段描述 备注 patientID Bigint 病人编号 主键 Jz_date Varchar 20 就时间 Pay varchar 10 缴费情况 病人就花费 Name varchar 20 姓名 非空 Sex char 10 性别 Age Int 年龄 床位bed 列名 数据类型 字段长度 字段描述 备注 Number Bigint 住号 主键 Name Varchar( 20 姓名 非空 Bedroom bigint 床号 Doctor Varchar 20 主治医生 主管本床位的医生姓名 Result Varchar 20 治疗结果 Department varchar 20 所属病区 病区department 列名 数据类型 字段长度 字段描述 备注 Depname varchar 10 病区名称 主键 Bedamount bigint 病床数 Responsor varchar 20 负责人姓名 非空 Inpeople bigint 入住人数 Wellpor real 好转率 Death real 、 死亡率 回访re_call 列名 数据类型 长度 字段描述 备注 Number bigint 序号 主键,自动产生 patientID bigint 病人编号 不为空 Callday varchar 20 回访时间 Callbody varchar 20 回访人 Record varchar 500 回访记录 Life char 8 生命特征 死亡 门病历ccase 列名 数据类型 字段长度 字段描述 备注 caesID Bigint 病历号 主键 Name Varchar 20 姓名 非空 Context Varchar 60 病例内容 Diadate datetime 断时间 Doctor Varchar 20 主治医生 联系 支付2pay2 列名 数据类型 字段长度 字段描述 备注 PatientID bigint 病人编号 主键 chargeID Bigint 支付项目号 主键 Amount varchar 20 payDate datetime 支付时间 收费项目2charge2 列名 数据类型 字段长度 字段描述 备注 chargeID bigint 项目序号 主键 Chargesort Varchar 20 项目类型 Amount Varchar 10 收费金额 Name Varchar 20 病人姓名 Operator Varchar 20 收款员 收费项目1charge1 列名 数据类型 字段长度 字段描述 备注 chargeID bigint 项目序号 主键 Name Varchar 20 病人姓名 number bigint 住号 外码 category Varchar 10 收费类型 chargeday datetime 收费日期 opertor varchar 20 收款人 Amount Varchar 10 应收金额 payamount Char 10 交费金额 入通知单inotice 列名 数据类型 字段长度 字段描述 备注 inoticeID bigint 通知单号 主键 doctor varchar 20 医师姓名 非空 Name varchar 20 病人姓名 非空 PatientID bigint 病人编号 外码 Diagadvice varchar 40 断建议 Pay varchar 20 收费情况 Pass Char 4 是否批准 是 否。非空 关系及各属性 Patient(patientID,name,sex,birth,dep,depadd,address,work,insure,insnumb,tel,email,deathday) Inpatient(number,patientID,name,inday,sort,bedroom) Outpatient(patientID,name ,sex,age,jz_date,pay) Bed(number,name,bedroom,doctor,result,department,empty) Department(depname,bedamount,responsor,inpeople,wellpor,,deathpor) Re_call(number,patientID,callday,life,record,callbody) Case(caseID,name,context,diadate,doctor) Charge2(chargeID,chargesort,amount,name,operator) Charge1(chargeID,category,name ,number,chargeday,payamount,amount) inotice(inoticeID,doctor,name,patientID,diaadvice,pay,pass) 联系 Pay2(patientID,amount,paydate,chargeID) 触发器 1提醒触发器 create trigger reminder on patient after insert,update as raiserror('你在插入或修改病人的数据',16,10); 2.更新操作的触发器 create trigger hehe on outpatient for update as begin update outpatient set pay=pay*0.9 end 存储过程 1病人信息插入的存储过程 create procedure patientInsert ( @patientID bigint, @name varchar(20), @sex char(4), @birth datetime, @dep varchar(40), @depadd varchar(60), @address varchar(60), @work varchar(10), @insure char(4), @insnumb varchar(30), @tel varchar(15), @email varchar(50), @deathday datetime ) as insert into patient( name,sex ,birth ,dep,depadd ,address ,work ,insure,insnumb ,tel ,email ,deathday ) values(@name,@sex ,@birth ,@dep,@depadd ,@address ,@work ,@insure,@insnumb ,@tel ,@email ,@deathday ) 2 住病人信息插入的存储过程 create procedure inpatientInsert ( @number bigint, @patientID bigint, @name varchar(20), @inday datetime, @sort char(20), @bedroom char(4) ) as insert into inpatient( number,patientID ,name ,inday ,sort ,bedroom ) values( @number ,@patientID ,@name ,@inday ,@sort ,@bedroom ) 索引 1 use hospital_patient create unique nonclustered index inpatient_name on inpatient ( name ) 2 use hospital_patient create nonclustered index charge_amount on charge1 ( amount desc )
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值