iOS网络编程笔记——编写自己的网络客户端

时间:2025-01-19 22:07:44

编写网络客户端主要有四个步骤:

(1)项目中引入Accounts和Social框架

Accounts框架中有进行用户账户认证所需类,Social框架提供了我们所需要的SLRequest类。

(2)用户账户认证

用户账户认证使用ACAccount、ACAccountStore和ACAccountType类,ACAccount类是封装用户账户信息,这些信息存储在账户数据库中。ACAccountStore类用来管理用户账户数据库,ACAccountType类用来描述账户类型。

(3)发送请求

用户认证通过就可以进行发送,使用SLRequest对象发送请求。

(4)处理请求结果

处理请求结果,解析数据更新ui

具体代码使用通过一个新浪微博例子:

微博列表类:

#import "WeiboListController.h"
#import <Social/Social.h>
#import <Accounts/Accounts.h> #define WEIBO_LIST @"https://api.weibo.com/2/statuses/user_timeline.json" @interface WeiboListController ()
/*
* 返回的微博列表
*/
@property (nonatomic, strong) NSArray *listData; @end @implementation WeiboListController - (void)viewDidLoad {
[super viewDidLoad];
//初始化UIRefreshControl
UIRefreshControl *rc = [[UIRefreshControl alloc] init];
rc.attributedTitle = [[NSAttributedString alloc] initWithString:@"下拉刷新"];
[rc addTarget:self action:@selector(refreshTableView) forControlEvents:UIControlEventValueChanged];
self.refreshControl = rc;
} - (void)refreshTableView
{
if (self.refreshControl.isRefreshing){
self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"加载中..."];
//创建一个ACAccountStore对象用来查询用户信息
ACAccountStore *account = [[ACAccountStore alloc] init];
//获得ACAccountType对象,参数为账户类型标识
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierSinaWeibo];
//请求访问用户账户信息,请求完成回调代码块
[account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) {
if (granted == YES){//认证通过
//返回所有特定类型标识账户信息
NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > ) {
ACAccount *weiboAccount = [arrayOfAccounts lastObject];
//设置请求参数 由社交网站提供
NSDictionary *parameters = [NSDictionary dictionaryWithObject:@"" forKey:@"count"];
NSURL *requestURL = [NSURL URLWithString:WEIBO_LIST];
//发送请求
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeSinaWeibo requestMethod:SLRequestMethodGET URL:requestURL parameters:parameters];
request.account = weiboAccount;//为请求对象设置账户信息
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
//处理请求结果
NSError *err;
if (!responseData){
return ;
}
id jsonObj = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&err];
if (!err) {
_listData = [jsonObj objectForKey:@"statuses"];
[self.tableView reloadData];
}
//停止下拉刷新
if (self.refreshControl) {
[self.refreshControl endRefreshing];
self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"下拉刷新"];
}
}];
}
}
}];
}
} #pragma mark - Table view data source - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.listData.count;
} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
NSDictionary *dict = self.listData[indexPath.row];
cell.textLabel.text = [dict objectForKey:@"text"];
cell.detailTextLabel.text = [dict objectForKey:@"created_at"];
return cell;
} @end

微博发送类:

//
// WeiboSendController.m
// Weibo
//
// Created by 王凯 on 17/3/1.
// Copyright © 2017年 王凯. All rights reserved.
// #import "WeiboSendController.h"
#import <Social/Social.h>
#import <Accounts/Accounts.h> @interface WeiboSendController ()<UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet UILabel *countLabel; @end @implementation WeiboSendController - (void)viewDidLoad {
[super viewDidLoad];
} #pragma mark -<UITextViewDelegate> - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
NSString *content = _textView.text;
NSInteger count = - [content length];
if (count < ) {
_countLabel.text = @"";
return NO;
}
_countLabel.text = [NSString stringWithFormat:@"%ld",count];
return YES;
} - (IBAction)sendBtnClick:(id)sender {
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierSinaWeibo];
[account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) {
if (granted == YES) {
NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > ) {
ACAccount *weiboAccount = [arrayOfAccounts lastObject];
NSDictionary *parameters = [NSDictionary dictionaryWithObject:_textView.text forKey:@"status"];
NSURL *requestURL = [NSURL URLWithString:@"https://api.weibo.com/2/statuses/update.json"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeSinaWeibo requestMethod:SLRequestMethodPOST URL:requestURL parameters:parameters];
request.account = weiboAccount;
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSLog(@"weibo http response:%ld",[urlResponse statusCode]);
}];
}
}
}];
//放弃第一响应者
[_textView resignFirstResponder];
//关闭模态视图
[self dismissViewControllerAnimated:YES completion:nil];
} - (IBAction)cancelBtnClick:(id)sender {
//放弃第一响应者
[_textView resignFirstResponder];
//关闭模态视图
[self dismissViewControllerAnimated:YES completion:nil];
}

iOS网络编程笔记——编写自己的网络客户端