当前位置: 首页 > 编程日记 > 正文

使用 AFNetworking 进行 XML 和 JSON 数据请求

(1)XML 数据请求

使用 AFNetworking 中的 AFHTTPRequestOperation 和 AFXMLParserResponseSerializer,另外结合第三方框架 XMLDictionary 进行数据转换

使用 XMLDictionary 的好处:有效避免自行实现 NSXMLParserDelegate 委托代理协议方法来进行繁琐的数据拼凑解析

(2)JSON 数据请求

使用 AFNetworking 中的 AFHTTPRequestOperation 或 AFHTTPRequestOperationManager,另外在图片缓存方面可选的方案有:

  • 使用 AFNetworking 中 的 UIImageView+AFNetworking

  • 使用第三方框架 SDWebImage 的 UIImageView+WebCache

效果如下:

XML 数据格式:

请求网址:http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName?theCityName=59287

 1 <ArrayOfString xmlns="http://WebXml.com.cn/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 2     <string>
 3         广东
 4     </string>
 5     <string>
 6         广州
 7     </string>
 8     <string>
 9         59287
10     </string>
11     <string>
12         59287.jpg
13     </string>
14     <string>
15         2015-9-19 17:30:31
16     </string>
17     <string>
18         25℃/32℃
19     </string>
20     <string>
21         9月19日 多云转中雨
22     </string>
23     <string>
24         无持续风向微风
25     </string>
26     <string>
27         1.gif
28     </string>
29     <string>
30         8.gif
31     </string>
32     <string>
33         今日天气实况:气温:31℃;风向/风力:西南风 1级;湿度:62%;空气质量:暂无;紫外线强度:弱
34     </string>
35     <string>
36         太阳镜指数:必要。建议佩戴透射比为1级的浅色太阳镜。
37 穿衣指数:炎热。建议穿短衫、短裤等清凉夏季服装。
38 旅游指数:适宜。微风,虽天气稍热,但不会影响心情。
39 运动指数:较适宜。户外运动请注意防晒。
40 洗车指数:不宜。有雨,雨水和泥水会弄脏爱车。
41 化妆指数:防脱水。请选用防脱水化妆品。
42 感冒指数:少发。感冒机率较低,避免长期处于空调屋中。
43 空气污染指数:暂无。
44 紫外线指数:弱。辐射较弱,涂擦SPF12-15、PA+护肤品。
45 舒适度指数:较不舒适。多云,有些热。
46     </string>
47     <string>
48         25℃/29℃
49     </string>
50     <string>
51         9月20日 中雨转中到大雨
52     </string>
53     <string>
54         无持续风向微风
55     </string>
56     <string>
57         8.gif
58     </string>
59     <string>
60         22.gif
61     </string>
62     <string>
63         24℃/29℃
64     </string>
65     <string>
66         9月21日 中到大雨转雷阵雨
67     </string>
68     <string>
69         无持续风向微风
70     </string>
71     <string>
72         22.gif
73     </string>
74     <string>
75         4.gif
76     </string>
77     <string>
78         广州是广东省的省会,是中国南方最大的海滨城市,广州位于东经113。17`,北纬23。8`,地处中国大陆南部,广东省南部,珠江三角洲北缘。广州临南海,邻近香港特别行政区,是中国通往世界的南大门,广州属丘陵地带。中国的第三大河----珠江从广州市中心穿流而过。广州是一座历史文化名城。相传在远古时候,曾有五位仙人,身穿五色彩服、骑着嘴衔稻穗的五色仙羊降临此地,把稻穗赠给百姓,祝愿这里永无饥荒。从此,广州便有“羊城”、“穗城”的美称,“五羊”也成为广州的象征。广州既是中国也是世界名城,又是一座古城,因历史上有五羊仙子降临献稻穗的故事,广州又称为“羊城”和“穗城”,简称“穗”;广州一年四季如春、繁花似锦,除夕迎春花市闻名海内外,故又有“花城”的美誉。广州地处低纬,属南亚热带季风气候区。地表接受太阳辐射量较多,同时受季风的影响,夏季海洋暖气流形成高温、高湿、多雨的气候;冬季北方大陆冷风形成低温、干燥、少雨的气候。年平均气温为21.4-21.9度,年降雨量平均为1623.6-1899.8mm,北部多于南部。1982年,广州被国务院选定为全国首批历史文化名城之一,是我国重点旅游城市。1999年1月,广州被评为优秀旅游城市。景观:白云山、莲花山、南海神庙、佛山祖庙、广州动物园等。
79     </string>
80 </ArrayOfString>
View Code

JSON 数据格式:

请求网址:https://alpha-api.app.net/stream/0/posts/stream/global

 1 {
 2     "data": [
 3         {
 4             "canonical_url": "https://alpha.app.net/hasskod2013/post/64791677",
 5             "created_at": "2015-09-19T11:23:30Z",
 6             "entities": {
 7                 "hashtags": [
 8                 ],
 9                 "links": [
10                     {
11                         "len": 21,
12                         "pos": 163,
13                         "text": "http://bit.ly/1Ynt5DC",
14                         "url": "http://bit.ly/1Ynt5DC"
15                     }
16                 ],
17                 "mentions": [
18                 ]
19             },
20             "html": "<span itemscope=\"https://app.net/schemas/Post\">Oman says ambassador's home hit in Yemen: Foreign ministry condemns incident in Sanaa as Arab coalition bombards Houthi-held sites as part of move to retake city. <a href=\"http://bit.ly/1Ynt5DC\">http://bit.ly/1Ynt5DC</a></span>",
21             "id": "64791677",
22             "machine_only": false,
23             "num_replies": 0,
24             "num_reposts": 0,
25             "num_stars": 0,
26             "pagination_id": "64791677",
27             "source": {
28                 "client_id": "8dWzbxxwZeTTAH3v7Yy9TbJ82W6mexqH",
29                 "link": "http://twitterfeed.com",
30                 "name": "twitterfeed"
31             },
32             "text": "Oman says ambassador's home hit in Yemen: Foreign ministry condemns incident in Sanaa as Arab coalition bombards Houthi-held sites as part of move to retake city. http://bit.ly/1Ynt5DC",
33             "thread_id": "64791677",
34             "user": {
35                 "avatar_image": {
36                     "height": 80,
37                     "is_default": false,
38                     "url": "https://d2rfichhc2fb9n.cloudfront.net/image/5/8crtOD1QaZ4b0uA6GnTQQMVTgJJ7InMiOiJzMyIsImIiOiJhZG4tdXNlci1hc3NldHMiLCJrIjoiYXNzZXRzL3VzZXIvMjMvZmIvNTAvMjNmYjUwMDAwMDAwMDAwMC5wbmciLCJvIjoiIn0",
39                     "width": 80
40                 },
41                 "canonical_url": "https://alpha.app.net/hasskod2013",
42                 "counts": {
43                     "followers": 16,
44                     "following": 33,
45                     "posts": 11722,
46                     "stars": 0
47                 },
48                 "cover_image": {
49                     "height": 260,
50                     "is_default": true,
51                     "url": "https://d2rfichhc2fb9n.cloudfront.net/image/5/kZ-JRmTbmd3WVPswTJ8Nwxzkf917InMiOiJzMyIsImIiOiJ0YXBwLWFzc2V0cyIsImsiOiJpL1UvaS9ZL1VpWW5xRFNvTUtyTEhLNXA0OHN2NkxmTmRVMC5qcGciLCJvIjoiIn0",
52                     "width": 960
53                 },
54                 "created_at": "2013-08-28T11:18:40Z",
55                 "id": "155975",
56                 "locale": "ar_AA",
57                 "name": "hasskod",
58                 "timezone": "Asia/Baghdad",
59                 "type": "feed",
60                 "username": "hasskod2013"
61             }
62         },
63         //同样格式的19个数组元素内容,这里省略...
64     ],
65     "meta": {
66         "code": 200,
67         "max_id": "64791677",
68         "min_id": "64791658",
69         "more": true
70     }
71 }
View Code

ViewController.h

1 #import <UIKit/UIKit.h>
2 
3 @interface ViewController : UITableViewController
4 @property (copy, nonatomic) NSArray *arrSampleName;
5 
6 - (instancetype)initWithSampleNameArray:(NSArray *)arrSampleName;
7 
8 @end 

ViewController.m

 1 #import "ViewController.h"
 2 #import "XMLRequestViewController.h"
 3 #import "JSONRequestViewController.h"
 4 
 5 @interface ViewController ()
 6 - (void)layoutUI;
 7 @end
 8 
 9 @implementation ViewController
10 - (void)viewDidLoad {
11     [super viewDidLoad];
12     
13     [self layoutUI];
14 }
15 
16 - (void)didReceiveMemoryWarning {
17     [super didReceiveMemoryWarning];
18     // Dispose of any resources that can be recreated.
19 }
20 
21 - (instancetype)initWithSampleNameArray:(NSArray *)arrSampleName {
22     if (self = [super initWithStyle:UITableViewStyleGrouped]) {
23         self.navigationItem.title = @"使用 AFNetworking 进行数据请求";
24         self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
25         
26         _arrSampleName = arrSampleName;
27     }
28     return self;
29 }
30 
31 - (void)layoutUI {
32     
33 }
34 
35 #pragma mark - UITableViewController相关方法重写
36 - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
37     return 0.1;
38 }
39 
40 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
41     return 1;
42 }
43 
44 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
45     return [_arrSampleName count];
46 }
47 
48 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
49     static NSString *cellIdentifier = @"cell";
50     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
51     if (!cell) {
52         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
53     }
54     cell.textLabel.text = _arrSampleName[indexPath.row];
55     return cell;
56 }
57 
58 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
59     switch (indexPath.row) {
60         case 0: {
61             XMLRequestViewController *XMLRequestVC = [XMLRequestViewController new];
62             [self.navigationController pushViewController:XMLRequestVC animated:YES];
63             break;
64         }
65         case 1: {
66             JSONRequestViewController *JSONRequestVC = [JSONRequestViewController new];
67             [self.navigationController pushViewController:JSONRequestVC animated:YES];
68             break;
69             
70             /*
71              类似堆栈的先进后出的原理:
72              返回到(上一级)、(任意级)、(根级)导航
73              [self.navigationController popViewControllerAnimated:YES];
74              [self.navigationController popToViewController:thirdSampleVC animated:YES];
75              [self.navigationController popToRootViewControllerAnimated:YES];
76              */
77         }
78         default:
79             break;
80     }
81 }
82 
83 @end 

PrefixHeader.pch

 1 #define kXMLRequestURLStr @"http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName?theCityName=59287"
 2 #define kJSONRequestURLStr @"https://alpha-api.app.net/stream/0/posts/stream/global"
 3 
 4 #define kTitleOfXMLRequest @"XML 数据请求"
 5 #define kTitleOfJSONRequest @"JSON 数据请求"
 6 
 7 #define kAvatarImageStr @"avatarImageStr"
 8 #define kName @"name"
 9 #define kText @"text"
10 #define kLink @"link"
11 #define kCreatedAt @"createdAt"
12 
13 #define kApplication [UIApplication sharedApplication] 

UIButton+BeautifulButton.h

 1 #import <UIKit/UIKit.h>
 2 
 3 @interface UIButton (BeautifulButton)
 4 /**
 5  *  根据按钮文字颜色,返回对应文字颜色的圆角按钮
 6  *
 7  *  @param tintColor 按钮文字颜色;nil 的话就为深灰色
 8  */
 9 - (void)beautifulButton:(UIColor *)tintColor;
10 
11 @end 

UIButton+BeautifulButton.m

 1 #import "UIButton+BeautifulButton.h"
 2 
 3 @implementation UIButton (BeautifulButton)
 4 
 5 - (void)beautifulButton:(UIColor *)tintColor {
 6     self.tintColor = tintColor ?: [UIColor darkGrayColor];
 7     self.layer.masksToBounds = YES;
 8     self.layer.cornerRadius = 10.0;
 9     self.layer.borderColor = [UIColor grayColor].CGColor;
10     self.layer.borderWidth = 1.0;
11 }
12 
13 @end 

NSString+OpenURL.h

 1 #import <UIKit/UIKit.h>
 2 
 3 @interface NSString (OpenURL)
 4 /**
 5  *  打开浏览器
 6  */
 7 - (void)openByBrowser;
 8 
 9 /**
10  *  打开邮件
11  */
12 - (void)openByEmail;
13 
14 /**
15  *  拨打电话
16  */
17 - (void)openByTelephone;
18 
19 /**
20  *  打开短信(Short Messaging Service)
21  */
22 - (void)openBySMS;
23 
24 @end 

NSString+OpenURL.m

 1 #import "NSString+OpenURL.h"
 2 
 3 @implementation NSString (OpenURL)
 4 
 5 + (void)open:(NSString *)openURLStr {
 6     [[UIApplication sharedApplication] openURL:[NSURL URLWithString:openURLStr]];
 7 }
 8 
 9 - (void)openByBrowser {
10     [NSString open:self];
11 }
12 
13 - (void)openByEmail {
14     [NSString open:[NSString stringWithFormat:@"mailto://%@", self]];
15 }
16 
17 - (void)openByTelephone {
18     [NSString open:[NSString stringWithFormat:@"tel://%@", self]];
19 }
20 
21 - (void)openBySMS {
22     [NSString open:[NSString stringWithFormat:@"sms://%@", self]];
23 }
24 
25 @end 

KMTableViewCell.h

 1 #import <UIKit/UIKit.h>
 2 
 3 @interface KMTableViewCell : UITableViewCell
 4 @property (strong, nonatomic) IBOutlet UIImageView *imgVAvatarImage;
 5 @property (strong, nonatomic) IBOutlet UILabel *lblName;
 6 @property (strong, nonatomic) IBOutlet UILabel *lblCreatedAt;
 7 @property (strong, nonatomic) IBOutlet UIImageView *imgVLink;
 8 
 9 @property (strong, nonatomic) UILabel *lblText;
10 @property (copy, nonatomic) NSString *avatarImageStr;
11 @property (copy, nonatomic) NSString *name;
12 @property (copy, nonatomic) NSString *text;
13 @property (copy, nonatomic) NSString *createdAt;
14 @property (assign, nonatomic, getter=isHaveLink) BOOL haveLink;
15 
16 @end 

KMTableViewCell.m

 1 #import "KMTableViewCell.h"
 2 //#import "UIImageView+AFNetworking.h"
 3 #import "UIImageView+WebCache.h"
 4 
 5 static UIImage *placeholderImage;
 6 static CGFloat widthOfLabel;
 7 @implementation KMTableViewCell
 8 
 9 - (void)awakeFromNib {
10     // Initialization code
11     static dispatch_once_t onceToken;
12     dispatch_once(&onceToken, ^{
13         placeholderImage = [UIImage imageNamed:@"JSON"];
14         widthOfLabel = [[UIScreen mainScreen] bounds].size.width - 100.0;
15     });
16     
17     _imgVAvatarImage.layer.masksToBounds = YES;
18     _imgVAvatarImage.layer.cornerRadius = 10.0;
19     
20     //由于 xib 中对标签自适应宽度找不到合适的方式来控制,所以这里用代码编写;这里屏幕复用的 Cell 有几个,就会执行几次 awakeFromNib 方法
21     _lblText = [[UILabel alloc] initWithFrame:CGRectMake(90.0, 23.0, widthOfLabel, 42.0)];
22     _lblText.numberOfLines = 2;
23     _lblText.font = [UIFont systemFontOfSize:12.0];
24     [self addSubview:_lblText];
25 }
26 
27 - (void)setSelected:(BOOL)selected animated:(BOOL)animated {
28     [super setSelected:selected animated:animated];
29 
30     // Configure the view for the selected state
31 }
32 
33 - (void)setAvatarImageStr:(NSString *)avatarImageStr {
34     if (![_avatarImageStr isEqualToString:avatarImageStr]) {
35         _avatarImageStr = [avatarImageStr copy];
36         NSURL *avatarImageURL = [NSURL URLWithString:_avatarImageStr];
37         //NSData *avatarImageData = [NSData dataWithContentsOfURL:avatarImageURL];
38         //_imgVAvatarImage.image = [UIImage imageWithData:avatarImageData];
39         
40         //图片缓存;性能优化的第一步
41         //方法一:AFNetworking 框架:UIImageView+AFNetworking
42 //        [_imgVAvatarImage setImageWithURL:avatarImageURL
43 //                         placeholderImage:placeholderImage];
44         
45         //方法二:SDWebImage 框架:UIImageView+WebCache
46         [_imgVAvatarImage sd_setImageWithURL:avatarImageURL
47                             placeholderImage:placeholderImage];
48     }
49 }
50 
51 - (void)setName:(NSString *)name {
52     _name = [name copy];
53     _lblName.text = _name;
54 }
55 
56 - (void)setText:(NSString *)text {
57     _text = [text copy];
58     _lblText.text = _text;
59 }
60 
61 - (void)setCreatedAt:(NSString *)createdAt {
62     _createdAt = [createdAt copy];
63     _lblCreatedAt.text = _createdAt;
64 }
65 
66 - (void)setHaveLink:(BOOL)haveLink {
67     _haveLink = haveLink;
68     _imgVLink.hidden = !_haveLink;
69 }
70 
71 @end 

KMTableViewCell.xib

 1 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
 2 <document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="7706" systemVersion="14E46" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES">
 3     <dependencies>
 4         <deployment identifier="iOS"/>
 5         <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="7703"/>
 6     </dependencies>
 7     <objects>
 8         <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
 9         <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
10         <tableViewCell contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" reuseIdentifier="cellIdentifier" rowHeight="101" id="KGk-i7-Jjw" customClass="KMTableViewCell">
11             <rect key="frame" x="0.0" y="0.0" width="375" height="101"/>
12             <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
13             <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="KGk-i7-Jjw" id="H2p-sc-9uM">
14                 <rect key="frame" x="0.0" y="0.0" width="320" height="43"/>
15                 <autoresizingMask key="autoresizingMask"/>
16                 <subviews>
17                     <imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="3Br-R7-YsD">
18                         <rect key="frame" x="0.0" y="5" width="80" height="80"/>
19                     </imageView>
20                     <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="name" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="kPR-pa-8uG">
21                         <rect key="frame" x="90" y="2" width="230" height="21"/>
22                         <fontDescription key="fontDescription" type="boldSystem" pointSize="14"/>
23                         <color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="calibratedRGB"/>
24                         <nil key="highlightedColor"/>
25                     </label>
26                     <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="created_at" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="iAH-dO-aus">
27                         <rect key="frame" x="90" y="64" width="130" height="21"/>
28                         <fontDescription key="fontDescription" type="system" pointSize="12"/>
29                         <color key="textColor" red="0.40000000596046448" green="0.40000000596046448" blue="0.40000000596046448" alpha="1" colorSpace="calibratedRGB"/>
30                         <nil key="highlightedColor"/>
31                     </label>
32                     <imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" image="Action_ReadOriginal" translatesAutoresizingMaskIntoConstraints="NO" id="By5-cw-IJd">
33                         <rect key="frame" x="223" y="60" width="30" height="30"/>
34                     </imageView>
35                 </subviews>
36             </tableViewCellContentView>
37             <connections>
38                 <outlet property="imgVAvatarImage" destination="3Br-R7-YsD" id="KaV-vS-y5p"/>
39                 <outlet property="imgVLink" destination="By5-cw-IJd" id="wrr-zz-EqH"/>
40                 <outlet property="lblCreatedAt" destination="iAH-dO-aus" id="BNF-es-fb1"/>
41                 <outlet property="lblName" destination="kPR-pa-8uG" id="BH7-oj-3Kx"/>
42             </connections>
43             <point key="canvasLocation" x="254.5" y="377.5"/>
44         </tableViewCell>
45     </objects>
46     <resources>
47         <image name="Action_ReadOriginal" width="60" height="60"/>
48     </resources>
49 </document>
View Code

XMLRequestViewController.h

1 #import <UIKit/UIKit.h>
2 
3 @interface XMLRequestViewController : UIViewController <NSXMLParserDelegate>
4 @property (strong, nonatomic) UITextView *txtVResult;
5 
6 @property (strong, nonatomic) IBOutlet UIButton *btnSendRequest;
7 
8 @end 

XMLRequestViewController.m

  1 #import "XMLRequestViewController.h"
  2 #import "AFNetworking.h"
  3 #import "AFNetworkActivityIndicatorManager.h"
  4 #import "UIButton+BeautifulButton.h"
  5 #import "XMLDictionary.h"
  6 
  7 @interface XMLRequestViewController ()
  8 - (void)layoutUI;
  9 - (void)convertXMLParserToDictionary:(NSXMLParser *)parser;
 10 @end
 11 
 12 @implementation XMLRequestViewController
 13 
 14 - (void)viewDidLoad {
 15     [super viewDidLoad];
 16     
 17     [self layoutUI];
 18 }
 19 
 20 - (void)didReceiveMemoryWarning {
 21     [super didReceiveMemoryWarning];
 22     // Dispose of any resources that can be recreated.
 23 }
 24 
 25 - (void)layoutUI {
 26     self.navigationItem.title = kTitleOfXMLRequest;
 27 
 28     [_btnSendRequest beautifulButton:nil];
 29     
 30     _txtVResult = [UITextView new];
 31     _txtVResult.editable = NO;
 32     CGRect rect = [[UIScreen mainScreen] bounds];
 33     _txtVResult.frame = CGRectMake(5.0, 64.0, rect.size.width - 10.0, rect.size.height - 164.0);
 34     _txtVResult.font = [UIFont systemFontOfSize:15.0];
 35     _txtVResult.text = @"点击「发送请求」按钮获取天气信息";
 36     [self.view addSubview:_txtVResult];
 37     
 38     //启动网络活动指示器;会根据网络交互情况,实时显示或隐藏网络活动指示器;他通过「通知与消息机制」来实现 [UIApplication sharedApplication].networkActivityIndicatorVisible 的控制
 39     [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
 40 }
 41 
 42 - (void)convertXMLParserToDictionary:(NSXMLParser *)parser {
 43     //dictionaryWithXMLParser: 是第三方框架 XMLDictionary 的方法
 44     NSDictionary *dic = [NSDictionary dictionaryWithXMLParser:parser];
 45     NSMutableString *mStrWeatherInfo = [[NSMutableString alloc] initWithString:@"广州近三天天气情况:\n"];
 46     NSArray *arrWeatherInfo = [dic objectForKey:@"string"];
 47     if (arrWeatherInfo != nil && arrWeatherInfo.count > 22) {
 48         NSMutableArray *mArrRange = [[NSMutableArray alloc] init];
 49         
 50         NSUInteger loc = mStrWeatherInfo.length;
 51         [mStrWeatherInfo appendFormat:@"\n %@", arrWeatherInfo[6]];
 52         NSUInteger len = mStrWeatherInfo.length - loc;
 53         NSValue *valObj = [NSValue valueWithRange:NSMakeRange(loc, len)];
 54         [mArrRange addObject:valObj];
 55         [mStrWeatherInfo appendFormat:@"\n %@", arrWeatherInfo[5]];
 56         [mStrWeatherInfo appendFormat:@"\n %@", arrWeatherInfo[7]];
 57         [mStrWeatherInfo appendFormat:@"\n %@", arrWeatherInfo[10]];
 58         
 59         loc = mStrWeatherInfo.length;
 60         [mStrWeatherInfo appendFormat:@"\n\n %@", arrWeatherInfo[13]];
 61         len = mStrWeatherInfo.length - loc;
 62         valObj = [NSValue valueWithRange:NSMakeRange(loc, len)];
 63         [mArrRange addObject:valObj];
 64         [mStrWeatherInfo appendFormat:@"\n %@", arrWeatherInfo[12]];
 65         [mStrWeatherInfo appendFormat:@"\n %@", arrWeatherInfo[14]];
 66         
 67         loc = mStrWeatherInfo.length;
 68         [mStrWeatherInfo appendFormat:@"\n\n %@", arrWeatherInfo[18]];
 69         len = mStrWeatherInfo.length - loc;
 70         valObj = [NSValue valueWithRange:NSMakeRange(loc, len)];
 71         [mArrRange addObject:valObj];
 72         [mStrWeatherInfo appendFormat:@"\n %@", arrWeatherInfo[17]];
 73         [mStrWeatherInfo appendFormat:@"\n %@", arrWeatherInfo[19]];
 74         
 75         [mStrWeatherInfo appendFormat:@"\n\n %@", arrWeatherInfo[22]];
 76         
 77         //数据的前10个字符以16.0像素加粗显示;这里使用 UITextView 的 attributedText,而他的 text 无法实现这种需求
 78         NSMutableAttributedString *mAttrStr = [[NSMutableAttributedString alloc] initWithString:mStrWeatherInfo];
 79         [mAttrStr addAttribute:NSFontAttributeName
 80                          value:[UIFont boldSystemFontOfSize:16.0]
 81                          range:NSMakeRange(0, 10)];
 82         
 83         //数据的日期部分以紫色显示
 84         for (NSValue *valObj in mArrRange) {
 85             NSRange currentRange;
 86             [valObj getValue:&currentRange];
 87             [mAttrStr addAttribute:NSForegroundColorAttributeName
 88                              value:[UIColor purpleColor]
 89                              range:currentRange];
 90         }
 91         
 92         //数据的前10个字符之后的内容全部以15.0像素显示
 93         [mAttrStr addAttribute:NSFontAttributeName
 94                          value:[UIFont systemFontOfSize:15.0]
 95                          range:NSMakeRange(10, mStrWeatherInfo.length - 10)];
 96         
 97         _txtVResult.attributedText = mAttrStr;
 98     } else {
 99         _txtVResult.text = @"请求数据无效";
100     }
101     
102 }
103 
104 - (IBAction)sendRequest:(id)sender {
105     NSURL *requestURL = [NSURL URLWithString:kXMLRequestURLStr];
106     NSURLRequest *request = [NSURLRequest requestWithURL:requestURL];
107     AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
108     op.responseSerializer = [AFXMLParserResponseSerializer serializer];
109     [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
110         NSLog(@"JSON: %@", responseObject);
111         NSXMLParser *parser = (NSXMLParser *)responseObject;
112         //这里使用了第三方框架 XMLDictionary,他本身继承并实现 NSXMLParserDelegate 委托代理协议,对数据进行遍历处理
113         [self convertXMLParserToDictionary:parser];
114         
115         //parser.delegate = self;
116         //parser.shouldProcessNamespaces = YES;
117         //[parser parse];
118     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
119         NSLog(@"Error: %@", error);
120     }];
121     //start 是 AFNetworking 的自定义方法,他在自定义的线程中去执行操作;不是 NSOperation 对象实例的 start 方法,所以可以不用使用把操作添加到操作主队列的方法:[[NSOperationQueue mainQueue] addOperation:op]
122     [op start];
123 }
124 
125 
126 #pragma mark -
127 #pragma mark NSXMLParserDelegate
128 /* 开始解析 XML 文件,在开始解析 XML 节点前,通过该方法可以做一些初始化工作 */
129 - (void)parserDidStartDocument:(NSXMLParser *)parser {
130     NSLog(@"开始解析 XML 文件");
131 }
132 
133 /* 当解析器对象遇到 XML 的开始标记时,调用这个方法开始解析该节点 */
134 - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
135     attributes:(NSDictionary *)attributeDict {
136     NSLog(@"发现节点:%@", elementName);
137 }
138 
139 /* 当解析器找到开始标记和结束标记之间的字符时,调用这个方法解析当前节点的所有字符 */
140 - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
141     NSLog(@"正在解析节点内容:%@", string);
142 }
143 
144 /* 当解析器对象遇到 XML 的结束标记时,调用这个方法完成解析该节点 */
145 - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
146     NSLog(@"解析节点结束:%@", elementName);
147 }
148 
149 /* 解析 XML 出错的处理方法 */
150 - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
151     NSLog(@"解析 XML 出错:%@", parseError);
152 }
153 
154 /* 解析 XML 文件结束 */
155 - (void)parserDidEndDocument:(NSXMLParser *)parser {
156     NSLog(@"解析 XML 文件结束");
157 }
158 
159 @end 

XMLRequestViewController.xib

 1 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
 2 <document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="7706" systemVersion="14E46" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES">
 3     <dependencies>
 4         <deployment identifier="iOS"/>
 5         <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="7703"/>
 6     </dependencies>
 7     <objects>
 8         <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="XMLRequestViewController">
 9             <connections>
10                 <outlet property="btnSendRequest" destination="zCQ-LM-grx" id="tgt-2z-WaB"/>
11                 <outlet property="view" destination="i5M-Pr-FkT" id="sfx-zR-JGt"/>
12             </connections>
13         </placeholder>
14         <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
15         <view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" id="i5M-Pr-FkT">
16             <rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
17             <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
18             <subviews>
19                 <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="zCQ-LM-grx">
20                     <rect key="frame" x="250" y="520" width="100" height="40"/>
21                     <constraints>
22                         <constraint firstAttribute="width" constant="100" id="V3R-30-5vV"/>
23                         <constraint firstAttribute="height" constant="40" id="yct-84-Mk4"/>
24                     </constraints>
25                     <state key="normal" title="发送请求">
26                         <color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/>
27                     </state>
28                     <connections>
29                         <action selector="sendRequest:" destination="-1" eventType="touchUpInside" id="8zG-Dl-erk"/>
30                     </connections>
31                 </button>
32             </subviews>
33             <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
34             <constraints>
35                 <constraint firstAttribute="bottom" secondItem="zCQ-LM-grx" secondAttribute="bottom" constant="40" id="DBx-zw-hdG"/>
36                 <constraint firstAttribute="centerX" secondItem="zCQ-LM-grx" secondAttribute="centerX" id="F2b-L7-BR9"/>
37             </constraints>
38         </view>
39     </objects>
40 </document>
View Code

JSONRequestViewController.h

 1 #import <UIKit/UIKit.h>
 2 
 3 @interface JSONRequestViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UIWebViewDelegate>
 4 @property (strong, nonatomic) NSMutableArray *mArrCell;
 5 @property (strong, nonatomic) UITableView *tableView;
 6 @property (strong, nonatomic) UILabel *lblEmptyDataMsg;
 7 @property (strong, nonatomic) UIWebView *webView;
 8 
 9 @property (strong, nonatomic) IBOutlet UIButton *btnSendRequest;
10 
11 @end 

JSONRequestViewController.m

  1 #import "JSONRequestViewController.h"
  2 #import "AFNetworking.h"
  3 #import "AFNetworkActivityIndicatorManager.h"
  4 #import "UIButton+BeautifulButton.h"
  5 #import "KMTableViewCell.h"
  6 #import "NSString+OpenURL.h"
  7 
  8 static NSString *cellIdentifier = @"cellIdentifier";
  9 @interface JSONRequestViewController ()
 10 - (void)layoutUI;
 11 - (NSString *)displayTimeFromCreatedAt:(NSString *)createdAt;
 12 - (void)loadData:(NSArray *)arrData;
 13 @end
 14 
 15 @implementation JSONRequestViewController
 16 
 17 - (void)viewDidLoad {
 18     [super viewDidLoad];
 19     
 20     [self layoutUI];
 21 }
 22 
 23 - (void)didReceiveMemoryWarning {
 24     [super didReceiveMemoryWarning];
 25     // Dispose of any resources that can be recreated.
 26 }
 27 
 28 - (void)layoutUI {
 29     self.navigationItem.title = kTitleOfJSONRequest;
 30     
 31     [_btnSendRequest beautifulButton:nil];
 32     
 33     _mArrCell = [[NSMutableArray alloc] initWithCapacity:0];
 34     
 35     CGRect rect = [[UIScreen mainScreen] bounds];
 36     CGRect frame = CGRectMake(5.0, 64.0, rect.size.width - 10.0, rect.size.height - 164.0);
 37     _tableView =[[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
 38     _tableView.dataSource = self;
 39     _tableView.delegate = self;
 40     //设置边距,解决单元格分割线默认偏移像素过多的问题
 41     if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {
 42         [_tableView setSeparatorInset:UIEdgeInsetsZero]; //设置单元格(上左下右)内边距
 43     }
 44     if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
 45         [_tableView setLayoutMargins:UIEdgeInsetsZero]; //设置单元格(上左下右)外边距
 46     }
 47     [self.view addSubview:_tableView];
 48     
 49     //注册可复用的单元格
 50     UINib *nib = [UINib nibWithNibName:@"KMTableViewCell" bundle:nil];
 51     [_tableView registerNib:nib forCellReuseIdentifier:cellIdentifier];
 52     
 53     //空数据时,显示的提示内容
 54     _lblEmptyDataMsg = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 300.0, 50.0)];
 55     CGPoint newPoint = _tableView.center;
 56     newPoint.y -= 45.0;
 57     _lblEmptyDataMsg.center = newPoint;
 58     _lblEmptyDataMsg.text = @"点击「发送请求」按钮获取全球新闻信息";
 59     _lblEmptyDataMsg.textColor = [UIColor grayColor];
 60     _lblEmptyDataMsg.textAlignment = NSTextAlignmentCenter;
 61     _lblEmptyDataMsg.font = [UIFont systemFontOfSize:16.0];
 62     [_tableView addSubview:_lblEmptyDataMsg];
 63     
 64     //点击单元格时,显示的新闻信息详细内容
 65     frame = CGRectMake(10.0, CGRectGetMidY(rect) - 200.0, rect.size.width - 20.0, 400.0);
 66     _webView = [[UIWebView alloc] initWithFrame:frame];
 67     _webView.layer.borderColor = [UIColor lightGrayColor].CGColor;
 68     _webView.layer.borderWidth = 1.0;
 69     _webView.delegate = self;
 70     _webView.hidden = YES;
 71     [self.view addSubview:_webView];
 72     
 73     [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
 74 }
 75 
 76 - (NSString *)displayTimeFromCreatedAt:(NSString *)createdAt {
 77     NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
 78     [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"]; //「2015-09-15T13:23:28Z」
 79     NSDate *date = [dateFormat dateFromString:createdAt];
 80     
 81     NSTimeZone *zone = [NSTimeZone systemTimeZone];
 82     NSInteger interval = [zone secondsFromGMTForDate:date]; //跟 GMT 时间相差8小时
 83     date = [date dateByAddingTimeInterval:interval];
 84     [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; //转化为「2015-09-15 21:23:28」
 85     NSString *displayTime = [dateFormat stringFromDate:date];
 86     return displayTime;
 87 }
 88 
 89 - (void)loadData:(NSArray *)arrData {
 90     _mArrCell = [NSMutableArray new];
 91     [arrData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
 92         NSMutableDictionary *mDicCell = [NSMutableDictionary new];
 93         NSDictionary *dicRoot = (NSDictionary *)obj;
 94         NSArray *arrLink = [dicRoot valueForKeyPath:@"entities.links"];
 95         [mDicCell setValue:[NSString stringWithFormat:@"%@?w=80&h=80",
 96                            [dicRoot valueForKeyPath:@"user.avatar_image.url"]]
 97                    forKey:kAvatarImageStr];
 98         [mDicCell setValue:[dicRoot valueForKeyPath:@"user.name"] forKey:kName];
 99         [mDicCell setValue:[dicRoot valueForKey:@"text"] forKey:kText];
100         [mDicCell setValue:(arrLink.count > 0 ? [arrLink[0] valueForKey:@"url"] : @"")
101                     forKey:kLink];
102         [mDicCell setValue:[self displayTimeFromCreatedAt:[dicRoot valueForKey:@"created_at"]]
103                     forKey:kCreatedAt];
104         [_mArrCell addObject:mDicCell];
105     }];
106     [self.tableView reloadData];
107 }
108 
109 - (IBAction)sendRequest:(id)sender {
110     _lblEmptyDataMsg.text = @"加载中...";
111     _webView.hidden = YES;
112     
113     //方法一:AFHTTPRequestOperation
114 //    NSURL *requestURL = [NSURL URLWithString:kJSONRequestURLStr];
115 //    NSURLRequest *request = [NSURLRequest requestWithURL:requestURL];
116 //    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
117 //    op.responseSerializer = [AFJSONResponseSerializer serializer];
118 //    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
119 //        NSDictionary *dic = (NSDictionary *)responseObject;
120 //        [self loadData:(NSArray *)dic[@"data"]];
121 //    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
122 //        NSLog(@"Error: %@", error);
123 //    }];
124 //    //start 是 AFNetworking 的自定义方法,他在自定义的线程中去执行操作;不是 NSOperation 对象实例的 start 方法,所以可以不用使用把操作添加到操作主队列的方法:[[NSOperationQueue mainQueue] addOperation:op]
125 //    [op start];
126     
127     //方法二:AFHTTPRequestOperationManager
128     AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
129     [manager GET:kJSONRequestURLStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
130         NSDictionary *dic = (NSDictionary *)responseObject;
131         [self loadData:(NSArray *)dic[@"data"]];
132     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
133         NSLog(@"Error: %@", error);
134     }];
135 }
136 
137 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
138     _webView.hidden = YES;
139 }
140 
141 #pragma mark - TableView
142 - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
143     return @"全球新闻信息列表";
144 }
145 
146 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
147     return 1;
148 }
149 
150 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
151     NSUInteger count = _mArrCell.count;
152     _lblEmptyDataMsg.hidden = count > 0;
153     
154     return count;
155 }
156 
157 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
158     KMTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
159     if (!cell) {
160         cell = [[KMTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
161                                       reuseIdentifier:cellIdentifier];
162     }
163     
164     NSMutableDictionary *mDicCell = _mArrCell[indexPath.row];
165     cell.avatarImageStr = mDicCell[kAvatarImageStr];
166     cell.name = mDicCell[kName];
167     cell.text = mDicCell[kText];
168     cell.createdAt = mDicCell[kCreatedAt];
169     cell.haveLink = [mDicCell[kLink] length] > 0; //可以通过 isHaveLink 或 haveLink 获取值
170     return cell;
171 }
172 
173 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
174     return 90.0;
175 }
176 
177 - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
178     /*
179      viewDidLoad 中对应的操作
180     if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {
181         [_tableView setSeparatorInset:UIEdgeInsetsZero]; //设置单元格(上左下右)内边距
182     }
183     if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
184         [_tableView setLayoutMargins:UIEdgeInsetsZero]; //设置单元格(上左下右)外边距
185     }
186      */
187     
188     if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
189         [cell setSeparatorInset:UIEdgeInsetsZero];
190     }
191     if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
192         [cell setLayoutMargins:UIEdgeInsetsZero];
193     }
194 }
195 
196 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
197     NSMutableDictionary *mDicCell = _mArrCell[indexPath.row];
198     NSString *link = mDicCell[kLink];
199     if (link.length > 0) {
200         //使用浏览器打开网址
201         //[link openByBrowser];
202         
203         //使用 WebView 打开网址;由于这里很多网址是外国的,存在有的访问不了、有的访问慢导致加载超时的情况
204         NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:link]];
205         [_webView loadRequest:request];
206         _webView.hidden = NO;
207     }
208 }
209 
210 #pragma mark - WebView
211 - (void)webViewDidStartLoad:(UIWebView *)webView {
212     kApplication.networkActivityIndicatorVisible = YES;
213 }
214 
215 - (void)webViewDidFinishLoad:(UIWebView *)webView {
216     kApplication.networkActivityIndicatorVisible = NO;
217 }
218 
219 - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
220     NSLog(@"Error: %@", error);
221     webView.hidden = YES;
222     kApplication.networkActivityIndicatorVisible = NO;
223     UIAlertView *alertVCustom = [[UIAlertView alloc] initWithTitle:@"提示信息"
224                                                            message:@"网络连接错误"
225                                                           delegate:nil
226                                                  cancelButtonTitle:@"确定"
227                                                  otherButtonTitles:nil, nil];
228     [alertVCustom show];
229 }
230 
231 @end

JSONRequestViewController.xib

 1 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
 2 <document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="7706" systemVersion="14E46" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES">
 3     <dependencies>
 4         <deployment identifier="iOS"/>
 5         <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="7703"/>
 6     </dependencies>
 7     <objects>
 8         <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="JSONRequestViewController">
 9             <connections>
10                 <outlet property="btnSendRequest" destination="zCQ-LM-grx" id="tgt-2z-WaB"/>
11                 <outlet property="view" destination="i5M-Pr-FkT" id="sfx-zR-JGt"/>
12             </connections>
13         </placeholder>
14         <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
15         <view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" id="i5M-Pr-FkT">
16             <rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
17             <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
18             <subviews>
19                 <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="zCQ-LM-grx">
20                     <rect key="frame" x="250" y="520" width="100" height="40"/>
21                     <constraints>
22                         <constraint firstAttribute="width" constant="100" id="V3R-30-5vV"/>
23                         <constraint firstAttribute="height" constant="40" id="yct-84-Mk4"/>
24                     </constraints>
25                     <state key="normal" title="发送请求">
26                         <color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/>
27                     </state>
28                     <connections>
29                         <action selector="sendRequest:" destination="-1" eventType="touchUpInside" id="8zG-Dl-erk"/>
30                     </connections>
31                 </button>
32             </subviews>
33             <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
34             <constraints>
35                 <constraint firstAttribute="bottom" secondItem="zCQ-LM-grx" secondAttribute="bottom" constant="40" id="DBx-zw-hdG"/>
36                 <constraint firstAttribute="centerX" secondItem="zCQ-LM-grx" secondAttribute="centerX" id="F2b-L7-BR9"/>
37             </constraints>
38         </view>
39     </objects>
40 </document>
View Code

AppDelegate.h

1 #import <UIKit/UIKit.h>
2 
3 @interface AppDelegate : UIResponder <UIApplicationDelegate>
4 
5 @property (strong, nonatomic) UIWindow *window;
6 @property (strong, nonatomic) UINavigationController *navigationController;
7 
8 @end 

AppDelegate.m

 1 #import "AppDelegate.h"
 2 #import "ViewController.h"
 3 
 4 @interface AppDelegate ()
 5 
 6 @end
 7 
 8 @implementation AppDelegate
 9 
10 
11 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
12     _window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
13     ViewController *viewController = [[ViewController alloc]
14                                       initWithSampleNameArray:@[ kTitleOfXMLRequest,
15                                                                  kTitleOfJSONRequest ]];
16     _navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
17     _window.rootViewController = _navigationController;
18     //[_window addSubview:_navigationController.view]; //当_window.rootViewController关联时,这一句可有可无
19     [_window makeKeyAndVisible];
20     return YES;
21 }
22 
23 - (void)applicationWillResignActive:(UIApplication *)application {
24 }
25 
26 - (void)applicationDidEnterBackground:(UIApplication *)application {
27 }
28 
29 - (void)applicationWillEnterForeground:(UIApplication *)application {
30 }
31 
32 - (void)applicationDidBecomeActive:(UIApplication *)application {
33 }
34 
35 - (void)applicationWillTerminate:(UIApplication *)application {
36 }
37 
38 @end

转载于:https://www.cnblogs.com/huangjianwu/p/4822072.html

相关文章:

批处理+定时任务实现定时休息提醒

前言&#xff1a;俗话说的好&#xff0c;懒是第一生产力&#xff0c;懒是提高生产效率的必要条件。而现今windows是大部分人的第一生产工具&#xff0c;批处理定时任务这对黄金搭档就是提升生产效率的第一工具。大家在生产过程中经常会遇到各种周期性的重复的工作&#xff0c;比…

后端返回的数据中换行符 html换行

标签代码 <span v-html"model3_txt"></span> vue js代码 var txt "恭喜你\n获得某某某奖品"; if(txt.indexOf(\n)!-1){var reg new RegExp("/r/n", "g");txttxt.replace(reg, "<br/>");console.log(t…

vim block vim_如何不再害怕Vim

vim block vim精选最流行的命令以及如何使用它们 (A curation of the most popular commands and how to use them) If you’ve ever used Vim, you know how difficult it can get to reach the same speed as in a “normal” GUI editor. But once you do, the payoff is ex…

android EditText 限定中文个数与英文个数的解决方式

EditText 限定中文8个英文16个的解决方法。 在EditText上控件提供的属性中有限定最大最小长度的方法。可是&#xff0c;对于输入时&#xff0c;限定中文8个英文16个时&#xff0c;怎么办&#xff1f;相当于一个中文的长度是两个英文的长度。原理就不说了。自己看一下android的源…

根据二叉树的前序遍历和中序遍历重建二叉树

题目描述 输入某二叉树的前序遍历和中序遍历的结果&#xff0c;请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}&#xff0c;则重建二叉树并返回。1 /**2 * Definition for …

VUE 监听当前路由 侦听器 watch

侦听器&#xff1a; 你可以利用侦听器&#xff0c;响应数据的变化&#xff0c;例如路由&#xff0c;和页面中data的值&#xff0c;可以在他们变化的时候写相应的处理逻辑在侦听器中。 侦听器的使用很简单&#xff1a; watch 对象就是侦听器&#xff0c;只有当侦听的值改变了它…

如何使用Bootstrap4和ES6创建自定义确认框

by Prashant Yadav通过Prashant Yadav 如何使用Bootstrap4和ES6创建自定义确认框 (How to create a custom confirm box with Bootstrap4 and ES6) We put lots of sweat into achieving a good design, but imagine a scenario where we have to use something which is styl…

RequireJS学习笔记(转)

前言进入移动前端是很不错的选择&#xff0c;这块也是我希望的道路&#xff0c;但是不熟悉啊。。。现在项目用的是requirebackbone&#xff0c;整个框架被封装了一次&#xff0c;今天看了代码搞不清楚&#xff0c;觉得应该先从源头抓起&#xff0c;所以再看看require了。上午是…

火狐中的table

在火狐浏览器中&#xff0c;table的th、td会存在小数转载于:https://www.cnblogs.com/likwin/p/7270817.html

React路由 react-router-dom

React的路由&#xff1a; 首先我们创建一个React应用 npm install -g create-react-app create-react-app demo-app cd demo-app安装路由 npm install react-router-dom npm add babel/runtime 接下来&#xff0c;将以下任一示例复制/粘贴到中src/App.js。 第一个示例&…

编程基础 垃圾回收_为什么我回收编程问题

编程基础 垃圾回收by Amy M Haddad通过艾米M哈达德(Amy M Haddad) 为什么我回收编程问题 (Why I Recycle Programming Problems) Many programmers are given the same advice: solve as many problems as possible. It’s true that solving new problems can help you gain …

SQL Server孤立账户解决办法

选择你想要的数据库。 执行 exec sp_change_users_login UPDATE_ONE,用户名,登录名 假如你的登录名是&#xff1a;sd exec sp_change_users_login UPDATE_ONE,sd,sd 转载于:https://www.cnblogs.com/runliuv/p/7273675.html

vue更新data无效,页面data没刷新 vue.set

Vue中组件的data是有很多坑的&#xff0c;先普及一下常识&#xff1a; 1.想使用data&#xff0c;必须先在data中创建。&#xff08;如果不创建就会报错&#xff09;示例&#xff1a; <div class"">{{user.Age}}</div>new Vue({el: #app,data: {user:{A…

重温Thinking in java

1、高精度 BigInteger、BigDecimal 支持任意大小的数字 不能使用运算符 运算速度相对于int、float稍慢 2、对象作用域 {String s new String("aaa"); } 在}外 此时栈中的引用s已经超出了自己的作用域 便不存在了 但是new String("aaa")这个堆中的对象仍然…

2018 react 大会_React Conf 2018的经验教训

2018 react 大会by Yangshun Tay阳顺泰 React Conf 2018的经验教训 (Lessons Learned at React Conf 2018) I was fortunate to have attended React Conf 2018 thanks to my managers — it was an awesome event. I have been watching past React Conf videos online and i…

删除url中某个参数

这里的url 是指一个网站链接 例如&#xff1a; https://baidu.com?a1&b2 下面看一下封装的代码 <!DOCTYPE html> <html><head><meta charset"utf-8"><script src"https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js&q…

【转载】MSXML应用总结 开发篇(下)

原文&#xff1a;http://blog.sina.com.cn/s/blog_48f93b530100eq4b.html 三、查询XML文档节点 这部分属于“读”XML文档并做节点遍历&#xff0c;由于担心加上实例会占用过多的篇幅影响阅读&#xff0c;先在这篇做方法总结&#xff0c;以后有时间再写一篇“实战篇”专门写个实…

d010:盈数、亏数和完全数

题目: 对一个正整数N而言&#xff0c;将它除了本身以外所有的因子加起来的总和为S&#xff0c;如果S>N&#xff0c;则N为盈数&#xff0c;如果S<N&#xff0c;则N为亏数&#xff0c;而如果SN&#xff0c;则N为完全数&#xff08;Perfect Number&#xff09;。例如10的因子…

软件开发 理想_我如何在12个月内找到理想的软件工作

软件开发 理想In this talk, Matt Woods shares the 3 cornerstone habits that helped him land his dream software job in just 12 months. These habits paved the way for him to consistently grow as a software developer, balloon his professional network, and easi…

Angular4.0从入门到实战打造在线竞拍网站学习笔记之四--数据绑定管道

Angular4.0基础知识之组件Angular4.0基础知识之路由Angular4.0依赖注入Angular4.0数据绑定&管道 数据绑定 数据绑定允许你将组件控制器的属性和方法与组件的模板连接起来&#xff0c;大大降低了开发时的编码量。 常见的表现形式有&#xff1a; 插值表达式&#xff1a;<h…

给GridView增加求和行

1、在WebForm窗体中&#xff0c;设置GridView的ShowFooter"True" 2、在后台代码中 private int jhrs0,ybrs0;//定义变量 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowIndex > 0) { jhrs Convert.ToInt16(e.Ro…

phpMyAdmin 数据库添加int类型的值时默认设为唯一主键的问题解决

数据库的表中插入了一条数据&#xff0c;再插入数据就插入不进去。 这是我今天在开发数据库的时候&#xff0c;遇到一个问题&#xff0c;经过排查&#xff0c;是数据库的结构有问题&#xff0c;有字段是唯一数据&#xff0c;但是目前还不想设置它的值。 场景环境描述&#xff…

python 类中定义类_Python中的动态类定义

python 类中定义类Here’s a neat Python trick you might just find useful one day. Let’s look at how you can dynamically define classes, and create instances of them as required.这是一个整洁的Python技巧&#xff0c;有一天可能会有用。 让我们看一下如何动态定义…

用自定义方法,传入成绩数组,实现输出考试成绩的成三名

package com.imooc; import java.util.Arrays; //导入Array类包 import java.util.Scanner; //导入Scanner类包 public class Final2 { public static void main(String args[]){Scanner…

EJS 什么是EJS后缀文件 EJS怎么用

一、什么是EJS EJS是一个JavaScript模板库&#xff0c;用来从JSON数据中生成HTML字符串。 二、为什么要使用EJS 与最初的JavaScript相比较&#xff0c;一些不太了解你的代码的人可以更容易地通过EJS模板代码看得懂你的代码。 让我们放松一下&#xff0c;一起来享受下令人激动的…

一个推荐系统,实现完整的设计-在百度搜索关键词推荐案例

在之前一篇博文中&#xff0c; 有同学在评论中问了个问题&#xff1a; 怎样解决因式分解带来的推荐冷门。热门关键词的问题。 在回答这个问题的时候&#xff0c; 想到了近几年在做搜索推荐系统的过程中&#xff0c; 学术界和工业界的一些差别。 正好近期正在做技术规划&#xf…

如何充分利用JavaScript(ES6)中的解构功能

by Joanna Gaudyn乔安娜高登(Joanna Gaudyn) Destructuring was a new addition to ES6. It took inspiration from languages like Python and allows you to extract data from arrays and objects into distinct variables. It might sound like something you’ve done in…

React 开发环境搭建

先来一个 React 官方文档的链接 点击跳转 搭建 React 的前期准备&#xff1a;你的本地环境需要安装 cnpm、node。 注&#xff1a;代码块中的 $ 代表&#xff1a; $后面是在命令行输入的命令&#xff0c;举例 $ npm start 解&#xff1a;实际上是应该打开命令行输入 npm st…

c++中的友元重载

1 语法 返回值类型 operator 运算符名称(形参列表) { 重载实体 } --------->operator和运算符名称在一起构造成新的函数名 2 案例 1 #include <iostream>2 3 using namespace std;4 5 class Complex6 {7 public:8 9 Complex(float x0,float y0) 10 :_…

WPF解析TTF 字体

偶遇需要自己解析 TTF 字体并显示&#xff0c;此做。。。 using System; using System.Collections.Generic; using System.Drawing.Text; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Windows; using System.W…