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

(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网络编程笔记——编写自己的网络客户端的更多相关文章

  1. Java基础知识强化之网络编程笔记10:TCP之客户端读取文本文件服务器控制台输出

    1. TCP之客户端读取文本文件服务器控制台输出 (1)客户端:(发送数据到服务端) package cn.itcast_10; import java.io.BufferedReader; impo ...

  2. Java基础知识强化之网络编程笔记09:TCP之客户端键盘录入服务器写到文本文件中

    1. TCP之客户端键盘录入服务器写到文本文件中 (1)客户端: package cn.itcast_09; import java.io.BufferedReader; import java.io ...

  3. Java基础知识强化之网络编程笔记08:TCP之客户端键盘录入服务器控制台输出

    1. 客户端: package cn.itcast_08; import java.io.BufferedReader; import java.io.BufferedWriter; import j ...

  4. Linux网络编程笔记(修订版)

    我的网络编程笔记, 因为最近又要做Linux下的网络编程,故重新修订, 其中一些内容参考了文末的链接及文章 1.   基本概念 2.   基本接口 2.1.   打开一个socket 2.2.   将 ...

  5. [C#网络编程系列]专题一:网络协议简介

    转自:http://www.cnblogs.com/zhili/archive/2012/08/11/NetWorkProgramming.html 因为这段时间都在研究C#网络编程的一些知识, 所以 ...

  6. 【TCP/IP网络编程】:01理解网络编程和套接字

    1.网络编程和套接字 网络编程与C语言中的printf函数和scanf函数以及文件的输入输出类似,本质上也是一种基于I/O的编程方法.之所以这么说,是因为网络编程大多是基于套接字(socket,网络数 ...

  7. iOS网络编程笔记——Socket编程

    一.什么是Socket通信: Socket是网络上的两个程序,通过一个双向的通信连接,实现数据的交换.这个双向连路的一端称为socket.socket通常用来实现客户方和服务方的连接.socket是T ...

  8. Winsock网络编程笔记(1)----入门

    今天第一次接触winsock网络编程,看的资料是Windows网络编程第二版.通过博客记住自己的看书笔记.. 在这里贴出第一个程序,虽然程序什么都没做,但以此作为入门,熟悉其网络编程风格.. #inc ...

  9. Go 网络编程笔记

    前言: 本文是学习<<go语言程序设计>> -- 清华大学出版社(王鹏 编著) 的2014年1月第一版 做的一些笔记 , 如有侵权, 请告知笔者, 将在24小时内删除, 转载请 ...

随机推荐

  1. Mybatis拦截器实现分页

    本文介绍使用Mybatis拦截器,实现分页:并且在dao层,直接返回自定义的分页对象. 最终dao层结果: public interface ModelMapper { Page<Model&g ...

  2. 2017qq红包雨最强攻略,

    这个只支持苹果手机,而且要有苹果电脑,只有苹果手机是不行的. QQ红包规则:只要你到达指定的位置,就可以领取附近的红包,一般也就几毛,还有几分的,当然也不排除有更高的,只不过我是没遇到... 那么既然 ...

  3. Windows下MySQL多实例安装/主从复制/重置密码

    Windows创建MySQL多实例 安装MYSQL和实例1 运行mysql-installer-community-5.7.16.0.msi 选择组件 MySQL Server 5.7.16 – X6 ...

  4. 神秘的ApplicationPoolIdentity再也不用妈妈担心程序池安全了

    在IIS 7和IIS 7.5中,我们可以为应用程序池设置一个特殊的Identity(用户标识):ApplicationPoolIdentity. 那么这个标识到底是什么意思?它是具体什么身份呢?这一讲 ...

  5. 从并发处理谈PHP进程间通信(一)外部介质

    .container { margin-right: auto; margin-left: auto; padding-left: 15px; padding-right: 15px } .conta ...

  6. ionic,Angular 开发实践

    1.实践参考 http://www.jianshu.com/p/ea0dcf1d31c9 原文思路搭建 2. 环境搭建步骤 : a. 安装node b.安装 cordova      sudo   n ...

  7. 【原创】NuGet 出现“无法初始化 PowerShell 主机,如果将你的 PowerShell 执行策略设置设置为 AllSigned ,请先打开程序包管理控制台以初始化该主机” 错误的解决方法

    现象: 网上的设置 AllSigned 等方法都无效..后来考虑可能跟命令行版本兼容性有关系,然后在注册表命令行配置里发现一 ForceV2 设置项,抱着试一试的心态改了下,果然解决了! 解决方法:修 ...

  8. devexpress控件layoutview特效之一旋转木马的实现

    1.devexpress有很多很好的特效,最近做了个旋转木马的特效,给大家分享下.效果图如下: 2.这里的控件为gridcontrol,里面的view为layoutview.数据绑定的代码与其他gri ...

  9. hive取数时如果遇到这种报错

    如果你hive取数时遇到这种报错:ParseException line 1:78 cannot recognize input near '<EOF>' '<EOF>' '& ...

  10. Javascript学习九

    计时器setInterval() 在执行时,从载入页面后每隔指定的时间执行代码. 语法: setInterval(代码,交互时间); 参数说明: 1. 代码:要调用的函数或要执行的代码串. 2. 交互 ...