首页 > 代码库 > iOS基础8:自定义MyData/自定义SQLite用于网络判断,版本判断,图片缓存处理,下载或者上传的GET或POST请求,加密手段,.数据解析
iOS基础8:自定义MyData/自定义SQLite用于网络判断,版本判断,图片缓存处理,下载或者上传的GET或POST请求,加密手段,.数据解析
MyDAta的.h文件
/*
MyData这一个基本上每个工程都能用到的Demo,他包含了很多内容:
1.iPhone机网络判断;
2.iPhone机软件版本判断(主要是看是否是大于IOS7);
3.图片缓存处理;
4.下载或者上传的GET或POST请求;
5.加密手段;
6.数据解析;
*/
//*****************************************************************************************
/*
宏定义SQL语句:
创建菜单数据存储表:
*/
#define MAPPINGDATA @"create table if not exists mapping(name text,title text)"//刷图记录表1
//******************************
#define SHAREDATA @"create table if not exists sharedata(name text,title text)"//分享记录表2
//******************************
#define JOBDATA @"create table if not exists job(name text,title text,integral text,taskId text)"//威客记录表3
//******************************
#define BRUSH @"create table if not exists brush(name text,taskid text,jifen text,url text)"//刷单记录表4
//********************
#define LEAFLETSDATA @"create table if not exists leaft(name text,taskid text,jifen text,url text)"//传单记录5
/*
给表中添加数据:
*/
#define TJSJMAPPINGDATA @"insert into mapping(name,title) values(?,?)"//添加数据于刷图记录表1
//********************************
#define TJSJSHAREDATA @"insert into sharedata(name,title) values(?,?)"//添加数据于分享记录表2
//********************************
#define TJSJJOBDATA @"insert into job(name,title,integral,taskId) values(?,?,?,?)"//添加数据于订单威客记录表3
//********************************
#define TJSJBRUSH @"insert into brush(name,taskid,jifen,url) values(?,?,?,?)"//添加数据于刷单记录表4
#define TJLEAFLETSDATA @"insert into leaft(name,taskid,jifen,keyword,url) values(?,?,?,?,?)"//添加传单与表中5
/*
读取表中数据:
*/
#define DQSJMAPPINGDATA @"select *from mapping"//读取刷图记录表1
#define DQSJSHAREDATA @"select *from sharedata"//读取分享记录表2
#define DQSJJOBDATA @"select *from job"//读取订单威客记录表3
#define DQSJBRUSH @"select *from brush"//读取订单表中刷单记录表4
#define DQLEAFLETSDATA @"select *from leaft"//读取传单表数据5
/*
删除表中所有数据:
*/
#define SCSJMAPPINGDATA @"delete from mapping"//删除食物表中数据1
#define SCSJSHAREDATA @"delete from sharedata"//删除订单表中数据2
#define SCSJJOBDATA @"delete from job"//删除订单表中数据3
#define SCSJBRUSH @"delete from brush"//删除订单表中数据4
#define SCSJLEAFLETSDATA @"delete from leaft"//删除传单中得数据5
//**********************************************************************************************
#import <Foundation/Foundation.h>
#import <sqlite3.h>
@protocol MyDataDelegate <NSObject>//定义一个协议
/*
参数:
datas ->返回数据;
ressNum ->下载完成度;0-1;
str ->访问地址;
*/
@optional
-(void)sendData:(NSMutableData *)datas andProgress:(float)ressNum andFilg:(NSString *)str andIndexPath:(NSIndexPath *)indexPath andError:(BOOL)error;
-(void)sendData:(NSMutableData *)datas andFilg:(NSString *)str andError:(BOOL)error;
-(void)sendData:(NSMutableData *)datas andProgress:(float)ressNum andFilg:(NSString *)str andError:(BOOL)error;
-(void)sendData:(NSMutableData *)datas andFilg:(NSString *)str andIndexPath:(NSIndexPath *)indexPath andError:(BOOL)error;
@end
@interface MyData :NSObject<NSURLConnectionDataDelegate>
/***********************************************************************
本工程变量定义:
************************************/
{
NSMutableData *receiveData;//用来记录数据data
NSString *urlstr;//用来记录网址
NSTimer *timer;//用来定时,设置缓冲时间
NSURLConnection *connection;//用来控制下载暂停
long long AllLength;//获取文件总长
}
@property(nonatomic,assign)id<MyDataDelegate>delegate;
@property(nonatomic,assign)NSIndexPath *indexPath;
/***********************************************************************
本工程固定比用方法定义:
************************************/
/*
判断系统是否是ios7;
*/
+(BOOL)isIos7;
+(BOOL)isIos6;
/*
图片缓存处理;
*/
+(NSString *)huoPathString:(NSString *)string;
+(NSString *)picturePath;//获取图片存储地址
+(BOOL)addpicture:(UIImage *)image andAddress:(NSString *)path;//将图片存入缓存文件夹
+(BOOL)judgeIsImage:(NSString *)path;//判断图片是否在文件夹中存在
+(UIImage *)obtainImage:(NSString *)path;//从文件夹中获取图片
+(BOOL)RemoveArrPictures;//删除所有图片
+(float)folderSizeAtPath;
/*
md5加密;
*/
+(NSString *)md5:(NSString *)str;
/*
下载数据方法;
*/
-(void)downloadGET:(NSString *)urlStr;//开始下载
-(void)stopDownload;//下载暂停
/*
POST请求;
*/
-(void)postUrl:(NSString *)url andString:(NSString *)string;
//-(void)postUrl:(NSString *)url andString:(NSString*)
/*
网络判断;
*/
+(BOOL)determineNetworkStatus;
/*
XML和JSON解析;
*/
+(void)jsonFor:(NSMutableArray *)array toIn:(NSData *)data;
+(void)xmlFor:(NSMutableArray *)array toIn:(NSData *)data;
/***********************************************************************
本工程非固定比用方法定义:
************************************/
/*
上传图片文件
*/
+(NSString *)postRequestWithURL:(NSString *)url
postParems:(NSMutableDictionary *)postParems
postImage:(UIImage *)image
fileName:(NSString *)name;
//+(BOOL)uploadJPEGImage:(UIImage *)image toUrl:(NSString *)url asFilename:(NSString *)filename postParems:(NSMutableDictionary *)postParems;
/*
数据库;
*/
//存数据
+(NSString *)filePath;
+(BOOL)cunMappingDataOfName:(NSString *)name andString:(NSString *)title;
+(BOOL)cunShareDataOfName:(NSString *)name andString:(NSString *)title;
+(BOOL)cunJobDateOfName:(NSString *)name andString:(NSString *)title andTTString:(NSString *)text andtaskId:(NSString *)taskId;
+(BOOL)cunBrushName:(NSString *)name andtaskId:(NSString *)taskId andJifen:(NSString *)jifen andUrl:(NSString *)urlStr;
+(BOOL)cunLeafName:(NSString *)name andtaskId:(NSString *)taskId andJifen:(NSString *)jifen andkeyWord:(NSString *)keyWord andUrl:(NSString *)urlStr;
//获取数据
+(NSMutableArray *)quMappingData;
+(NSMutableArray *)quShareData;
+(NSMutableArray *)quJobData;
+(NSMutableArray *)quBrushData;
+(NSMutableArray *)quLeafData;
//删除数据
+(BOOL)shanMappingData;
+(BOOL)shanShareData;
+(BOOL)shanJobData;
+(BOOL)shanBrushData;
+(BOOL)shanLeafDat
//==================================.m文件===========================
/*
MyData这一个基本上每个工程都能用到的Demo,他包含了很多内容:
1.iPhone机网络判断;
2.iPhone机软件版本判断(主要是看是否是大于IOS7);
3.图片缓存处理;
4.下载或者上传的GET或POST请求;
5.加密手段;
6.数据解析;
*/
#import "MyData.h"
#import <CommonCrypto/CommonDigest.h>
#import "Reachability.h"
#import "JSON.h"
#import "GDataXMLNode.h"
@implementation MyData
static sqlite3 *db=nil;//声明一个sqlite3数据库
static NSString *const FORM_FLE_INPUT = @"uploadFile";//声明一个未上传数据常量
//版本判断******************************************************************************
NSUInteger DeviceSystemMajorVersion();
NSUInteger DeviceSystemMajorVersion()
{
static NSUInteger _deviceSystemMajorVersion = -1;
//GCD单列用(得到唯一的版本号)
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_deviceSystemMajorVersion = [[[[[UIDevicecurrentDevice] systemVersion]componentsSeparatedByString:@"."]objectAtIndex:0]intValue];
});
return _deviceSystemMajorVersion;
}
//是否大于等于ios7
+(BOOL)isIos7
{
if ((DeviceSystemMajorVersion() >=7)) {
return YES;
}else{
return NO;
}
}
//是否大于等于ios6
+(BOOL)isIos6
{
if ((DeviceSystemMajorVersion() >=6)) {
return YES;
}else{
return NO;
}
}
//图片处理*******************************************************************************
+(NSString *)picturePath
{
//保存在沙箱
NSString *path=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES)lastObject];
//沙箱路径追加文件名
path=[path stringByAppendingPathComponent:@"图片缓存"];
NSFileManager *fm=[NSFileManagerdefaultManager];//文件管理器(处理文件分配、保存,读取)
//判读文件路径是否存在
if ([fm fileExistsAtPath:path]==NO)
{
//就创建文件路径
[fm createDirectoryAtPath:pathwithIntermediateDirectories:YESattributes:nilerror:nil];
}
return path;
}
+(NSString *)picturesName:(NSString *)path//利用图片的url生成图片的名称:
{
if ([path hasSuffix:@".bmp"]||[pathhasSuffix:@".jpg"]||[pathhasSuffix:@".tiff"]||[pathhasSuffix:@".gif"]||[path hasSuffix:@".pcx"]||[pathhasSuffix:@".png"]||[pathhasSuffix:@".jpeg"])
{
NSMutableString *str=[NSMutableStringstringWithString:path];
for (int i=path.length-1; i>=0; i--)
{
if ([str characterAtIndex:i]==‘/‘) {
[str deleteCharactersInRange:NSMakeRange(i,1)];
}
}
return str;
}
else
{
NSMutableString *str=[NSMutableStringstringWithString:[path stringByAppendingString:@".png"]];
for (int i=path.length-1; i>=0; i--)
{
if ([str characterAtIndex:i]==‘/‘) {
[str deleteCharactersInRange:NSMakeRange(i,1)];
}
}
return str;
}
}
+(BOOL)addpicture:(UIImage *)image andAddress:(NSString *)path
{
NSFileManager *file=[NSFileManagerdefaultManager];//定义文件
NSString *pp=[MyDatapicturePath];
NSString *lujing=[ppstringByAppendingPathComponent:[MyDatapicturesName:path]];//创建文件路径
NSData *data=http://www.mamicode.com/UIImagePNGRepresentation(image);//将图片转换为NSData格式
BOOL flay=[filecreateFileAtPath:lujing contents:dataattributes:nil];//创建文件
return flay;
}
+(BOOL)judgeIsImage:(NSString *)path
{
NSString *str=[MyDatapicturesName:path];
NSString *str_1=[MyDatapicturePath];
NSString *string=[str_1stringByAppendingPathComponent:str];
NSFileManager *manager=[NSFileManagerdefaultManager];
if ([manager fileExistsAtPath:string]==YES)
{
return YES;
}
else
{
return NO;
}
}
+(UIImage *)obtainImage:(NSString *)path
{
NSFileManager *file=[NSFileManagerdefaultManager];//定义文件
NSString *pp=[MyDatapicturePath];
NSString *lujing=[ppstringByAppendingPathComponent:[MyDatapicturesName:path]];//创建文件路径
NSData *data=http://www.mamicode.com/[file contentsAtPath:lujing];
UIImage *image=[UIImageimageWithData:data];
return image;
}
+(NSString *)huoPathString:(NSString *)string
{
NSString *pp=[MyDatapicturePath];
return [ppstringByAppendingPathComponent:[MyDatapicturesName:string]];//创建文件路径
}
+(BOOL)RemoveArrPictures
{
NSError *error=nil;
NSString *path=[MyDatapicturePath];
NSFileManager *fileManager=[NSFileManagerdefaultManager];
[fileManager removeItemAtPath:path error:&error];
return YES;
}
//md5加密***************************************************************
+(NSString *)md5:(NSString *)str
{
const char *cStr = [strUTF8String];
unsigned char result[32];
CC_MD5( cStr, strlen(cStr), result );
return [NSStringstringWithFormat:
@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
];
}
//下载数据*********************************************************
-(void)downloadGET:(NSString *)urlStr
{
NSURL *url=[NSURLURLWithString:urlStr];
NSURLRequest *request=[NSURLRequestrequestWithURL:url];
connection=[NSURLConnectionconnectionWithRequest:request delegate:self];
// timer=[NSTimer scheduledTimerWithTimeInterval:40.0 target:self selector:@selector(TerminationOfTheThread:) userInfo:nil repeats:NO];
}
-(void)stopDownload
{
[connection cancel];//取消下载
}
-(void)TerminationOfTheThread:(NSTimer *)timer1
{
if ([self.delegaterespondsToSelector:@selector(sendData:andProgress:andFilg:andIndexPath:andError:)]) {
[self.delegatesendData:nilandProgress:0andFilg:@"访问超时"andIndexPath:nilandError:YES];
}
if ([self.delegaterespondsToSelector:@selector(sendData:andProgress:andFilg:andError:)]) {
[self.delegatesendData:nilandProgress:0andFilg:@"访问超时"andError:YES];
}
if ([self.delegaterespondsToSelector:@selector(sendData:andFilg:andIndexPath:andError:)]) {
[self.delegatesendData:nilandFilg:@"访问超时"andIndexPath:self.indexPathandError:YES];
}
if ([self.delegaterespondsToSelector:@selector(sendData:andFilg:andError:)]) {
[self.delegatesendData:nilandFilg:@"访问超时"andError:YES];
}
[connection cancel];//停止下载
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{//将要下载时执行
receiveData=[[NSMutableDataalloc]initWithCapacity:0];
AllLength=[responseexpectedContentLength];
urlstr=[[response URL]absoluteString];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{//正在下载时执行
[receiveData appendData:data];
long long currentDataLength=[receiveDatalength];
float proportion=(float)currentDataLength/(float)AllLength;
if ([self.delegaterespondsToSelector:@selector(sendData:andProgress:andFilg:andIndexPath:andError:)]) {
[self.delegatesendData:receiveDataandProgress:proportion andFilg:urlstrandIndexPath:self.indexPathandError:NO];
}
if ([self.delegaterespondsToSelector:@selector(sendData:andProgress:andFilg:andError:)]) {
[self.delegatesendData:receiveDataandProgress:proportion andFilg:urlstrandError:NO];
}
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{//下载完成时执行
NSLog(@"3333333333333333");
if ([self.delegaterespondsToSelector:@selector(sendData:andProgress:andFilg:andIndexPath:andError:)]) {
[self.delegatesendData:receiveDataandProgress:1andFilg:urlstrandIndexPath:nilandError:NO];
}
if ([self.delegaterespondsToSelector:@selector(sendData:andProgress:andFilg:andError:)]) {
[self.delegatesendData:receiveDataandProgress:1andFilg:urlstrandError:NO];
}
if ([self.delegaterespondsToSelector:@selector(sendData:andFilg:andIndexPath:andError:)]) {
[self.delegatesendData:receiveDataandFilg:urlstrandIndexPath:self.indexPathandError:NO];
}
if ([self.delegaterespondsToSelector:@selector(sendData:andFilg:andError:)]) {
[self.delegatesendData:receiveDataandFilg:urlstrandError:NO];
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{//错误时!!!!!!!!!!!!!
NSLog(@"444444444444444");
if ([self.delegaterespondsToSelector:@selector(sendData:andProgress:andFilg:andIndexPath:andError:)]) {
[self.delegatesendData:nilandProgress:0andFilg:@"访问超时"andIndexPath:nilandError:YES];
}
if ([self.delegaterespondsToSelector:@selector(sendData:andProgress:andFilg:andError:)]) {
[self.delegatesendData:nilandProgress:0andFilg:@"访问超时"andError:YES];
}
if ([self.delegaterespondsToSelector:@selector(sendData:andFilg:andIndexPath:andError:)]) {
[self.delegatesendData:nilandFilg:@"访问超时"andIndexPath:self.indexPathandError:YES];
}
if ([self.delegaterespondsToSelector:@selector(sendData:andFilg:andError:)]) {
[self.delegatesendData:nilandFilg:@"访问超时"andError:YES];
}
}
//Post
//网络判断*******************************************************************************
+(BOOL)determineNetworkStatus
{
BOOL flay;
Reachability *r=[ReachabilityreachabilityForInternetConnection];
switch ([rcurrentReachabilityStatus]) {
caseNotReachable:
flay=NO;
break;
caseReachableViaWiFi:
flay=YES;
break;
caseReachableViaWWAN:
flay=YES;
break;
default:
break;
}
if (!flay) {
UIAlertView *alert=[[UIAlertViewalloc]initWithTitle:@"提示"message:@"没有检测到网络"delegate:selfcancelButtonTitle:@"知道了~"otherButtonTitles:nil];
[alert show];
}
return flay;
}
//POST请求****************************************************************************
-(void)postUrl:(NSString *)url andString:(NSString *)string
{
// NSLog(@"4444444444444");
NSMutableData *postData=http://www.mamicode.com/[[NSMutableDataalloc]init];
[postData appendData:[stringdataUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:[NSURLURLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheDatatimeoutInterval:20.0];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
connection=[NSURLConnectionconnectionWithRequest:request delegate:self];
NSLog(@"========%@",request);
// timer=[NSTimer scheduledTimerWithTimeInterval:20.0 target:self selector:@selector(TerminationOfTheThread:) userInfo:nil repeats:NO];
}
//JSON和XML解析***********************************************************************
+(void)jsonFor:(NSMutableArray *)array toIn:(NSData *)data
{
[array removeAllObjects];
//方法一:(系统提供方法)
NSArray *arr=[NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingAllowFragmentserror:nil];
[array setArray:arr];
//方法二:(第三方提供方法“JSON.h”)
NSString *str=[[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];
[array setArray:[str JSONValue]];
}
+(void)xmlFor:(NSMutableArray *)array toIn:(NSData *)data
{
[array removeAllObjects];
NSError *error=nil;
GDataXMLDocument *document=[[GDataXMLDocumentalloc]initWithData:dataoptions:0 error:&error];
GDataXMLElement *element=[document rootElement];
NSArray *eArray=[element elementsForName:@"student"];
for (GDataXMLElement *ein eArray) {
NSMutableDictionary *dic=[[NSMutableDictionaryalloc]init];
GDataXMLElement *subE1=[[e elementsForName:@"name"] lastObject];
[dic setObject:[subE1 stringValue] forKey:@"name"];
GDataXMLElement *subE2=[[e elementsForName:@"age"] lastObject];
[dic setObject:[subE2 stringValue] forKey:@"age"];
GDataXMLElement *subE3=[[e elementsForName:@"sex"] lastObject];
[dic setObject:[subE3 stringValue] forKey:@"sex"];
[array addObject:dic];
}
}
//单个文件的大小********************************************************
+(long long)fileSizeAtPath:(NSString*) filePath{
NSFileManager* manager = [NSFileManagerdefaultManager];
if ([manager fileExistsAtPath:filePath]){
return [[managerattributesOfItemAtPath:filePath error:nil]fileSize];
}
return 0;
}
+(float)folderSizeAtPath
{
NSFileManager* manager = [NSFileManagerdefaultManager];
if (![manager fileExistsAtPath:[MyData picturePath]])
{
return 0;
}
NSEnumerator *childFilesEnumerator = [[managersubpathsAtPath:[MyDatapicturePath]] objectEnumerator];
NSString* fileName;
long long folderSize =0;
while ((fileName = [childFilesEnumerator nextObject]) != nil){
NSString* fileAbsolutePath = [[MyDatapicturePath] stringByAppendingPathComponent:fileName];
folderSize += [MyData fileSizeAtPath:fileAbsolutePath];
}
return folderSize/(1024.0*1024.0);
}
//+(BOOL)uploadJPEGImage:(UIImage *)image toUrl:(NSString *)url asFilename:(NSString *)filename postParems:(NSMutableDictionary *)postParems
//{
// NSString *TWITTERFON_FORM_BOUNDARY = @"0xKhTmLbOuNdArY";
//
// //分界线 --AaB03x
// NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
// //结束符 AaB03x--
// NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
//
//
//
//
//
//
//
// //取得图形数据
// NSData *imageData=http://www.mamicode.com/UIImageJPEGRepresentation(image, 0.1);
//
// //试用post上传到服务器上
// NSMutableURLRequest *request=[[NSMutableURLRequest alloc]init];
// [request setURL:[NSURL URLWithString:url]];
// [request setHTTPMethod:@"POST"];
//
// //设置content type
// NSString *boundary=[NSString stringWithFormat:@"----------------------------%ld",random()];
//
// NSString *contentType=[NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
// [request addValue:contentType forHTTPHeaderField:@"Content-Type"];
//
// //设置body
// NSMutableData *body=[NSMutableData data];
//
//
// NSMutableString *bodyb=[[NSMutableString alloc]init];
// //参数的集合的所有key的集合
// NSArray *keys= [postParems allKeys];
//
// //遍历keys
// for(int i=0;i<[keys count];i++)
// {
// //得到当前key
// NSString *key=[keys objectAtIndex:i];
//
// //添加分界线,换行
// [bodyb appendFormat:@"%@\r\n",MPboundary];
// //添加字段名称,换2行
// [bodyb appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
// //添加字段的值
// [bodyb appendFormat:@"%@\r\n",[postParems objectForKey:key]];
//
// NSLog(@"添加字段的值==%@",[postParems objectForKey:key]);
// }
//
// //声明myRequestData,用来放入http body
//
//
// //将body字符串转化为UTF8格式的二进制
//
//
//
//
// [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//
//
// [body appendData:[bodyb dataUsingEncoding:NSUTF8StringEncoding]];
//
//
// [body appendData:[[NSString stringWithFormat:@"Content-Disposition:form-data;name=\"imageFilename\";filename=\"%@\"\r\n",filename] dataUsingEncoding:NSUTF8StringEncoding]];
// [body appendData:[@"Content-Type:application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// [body appendData:imageData];
// [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//
//
//
//
// [request setHTTPBody:body];
//
// //连接到服务器
// NSData *returnData=http://www.mamicode.com/[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//
// NSString *returnString=[[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];
// if ([returnString compare:@"YES"]==NSOrderedSame) {
// return YES;
// }else{
// return NO;
// }
//}
+(NSString *)postRequestWithURL:(NSString *)url
postParems:(NSMutableDictionary *)postParems
postImage:(UIImage *)image
fileName:(NSString *)name
{
NSString *TWITTERFON_FORM_BOUNDARY = @"0xKhTmLbOuNdArY";
//根据url初始化request
NSMutableURLRequest* request = [NSMutableURLRequestrequestWithURL:[NSURLURLWithString:url]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:10];
//分界线 --AaB03x
NSString *MPboundary=[[NSStringalloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
//结束符 AaB03x--
NSString *endMPboundary=[[NSStringalloc]initWithFormat:@"%@--",MPboundary];
NSData* data;
if(image){
//判断图片是不是png格式的文件
if (UIImagePNGRepresentation(image)) {
//返回为png图像。
NSLog(@"返回png");
// data = http://www.mamicode.com/UIImagePNGRepresentation(image);
data = http://www.mamicode.com/UIImageJPEGRepresentation(image,0.1);
}else {
//返回为JPEG图像。
NSLog(@"返回jpeg");
data = http://www.mamicode.com/UIImageJPEGRepresentation(image,0.1);
}
}
NSLog(@"---------%d",data.length);
//http body的字符串
NSMutableString *body=[[NSMutableStringalloc]init];
//参数的集合的所有key的集合
NSArray *keys= [postParems allKeys];
//遍历keys
for(int i=0;i<[keyscount];i++)
{
//得到当前key
NSString *key=[keys objectAtIndex:i];
//添加分界线,换行
[body appendFormat:@"%@\r\n",MPboundary];
//添加字段名称,换2行
[body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
//添加字段的值
[body appendFormat:@"%@\r\n",[postParemsobjectForKey:key]];
NSLog(@"添加字段的值==%@",[postParemsobjectForKey:key]);
}
if(image){
////添加分界线,换行
[body appendFormat:@"%@\r\n",MPboundary];
//声明pic字段,文件名为boris.png
[body appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",FORM_FLE_INPUT,name];
//声明上传文件的格式
[body appendFormat:@"Content-Type: image/jpg\r\n\r\n"];
}
//声明结束符:--AaB03x--
NSString *end=[[NSStringalloc]initWithFormat:@"\r\n%@",endMPboundary];
//声明myRequestData,用来放入http body
NSMutableData *myRequestData=http://www.mamicode.com/[NSMutableDatadata];
//将body字符串转化为UTF8格式的二进制
[myRequestData appendData:[bodydataUsingEncoding:NSUTF8StringEncoding]];
if(image){
//将image的data加入
[myRequestData appendData:data];
}
//加入结束符--AaB03x--
[myRequestData appendData:[enddataUsingEncoding:NSUTF8StringEncoding]];
//设置HTTPHeader中Content-Type的值
NSString *content=[[NSStringalloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
//设置HTTPHeader
[request setValue:contentforHTTPHeaderField:@"Content-Type"];
//设置Content-Length
[request setValue:[NSStringstringWithFormat:@"%d", [myRequestDatalength]] forHTTPHeaderField:@"Content-Length"];
//设置http body
[request setHTTPBody:myRequestData];
//http method
[request setHTTPMethod:@"POST"];
NSHTTPURLResponse *urlResponese = nil;
NSError *error = [[NSErroralloc]init];
NSData* resultData = http://www.mamicode.com/[NSURLConnectionsendSynchronousRequest:request returningResponse:&urlResponese error:&error];
NSString* result= [[NSStringalloc] initWithData:resultDataencoding:NSUTF8StringEncoding];
NSLog(@"%@",result);
NSLog(@"%d",[urlResponesestatusCode]);
if([urlResponese statusCode] >=200&&[urlResponese statusCode]<300){
NSLog(@"返回结果=====%@",result);
return result;
}
return nil;
}
//数据库文件的路径。一般在沙箱的Documents里边操作
+(NSString *)filePath
{
NSString *path=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES)lastObject];
path=[path stringByAppendingPathComponent:@"shuJu.sqlite"];
return path;
}
//创建表单
+(BOOL)chuangJianTable:(NSString *)string
{
sqlite3_open([[MyDatafilePath] UTF8String], &db);
if(!db)
{
NSLog(@"数据库打开失败!");
return NO;
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare_v2(db, [stringUTF8String], -1, &stmt,nil);
if (result==SQLITE_OK)
{
if (sqlite3_step(stmt)==SQLITE_DONE)//是程序数据库运行一步!
{
NSLog(@"创建成功!");
}
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}
+(BOOL)cunMappingDataOfName:(NSString *)name andString:(NSString *)title
{
[MyDatachuangJianTable:MAPPINGDATA];
sqlite3_open([[MyDatafilePath] UTF8String], &db);
if (!db)
{
NSLog(@"数据库打开失败!");
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare(db,[TJSJMAPPINGDATAUTF8String], -1, &stmt,nil);
if (result==SQLITE_OK)
{
//给问号赋值1,2,3,表示第几个问号
if (name.length>0) {
sqlite3_bind_text(stmt, 1, [name UTF8String], -1,nil);
}else{
sqlite3_bind_text(stmt, 1, [@"100" UTF8String], -1, nil);
}
if (title.length>0) {
sqlite3_bind_text(stmt, 2, [title UTF8String], -1,nil);
}else{
sqlite3_bind_text(stmt, 2, [@"你镔哥哥"UTF8String], -1,nil);
}
}
if (sqlite3_step(stmt)==SQLITE_DONE)//是程序数据库运行一步!
{
NSLog(@"添加成功!");
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}
//传单记录
+(BOOL)cunLeafName:(NSString *)name andtaskId:(NSString *)taskId andJifen:(NSString *)jifen andkeyWord:(NSString *)keyWord andUrl:(NSString *)urlStr
{
[MyDatachuangJianTable:chuandanURL];
sqlite3_open([[MyDatafilePath] UTF8String], &db);
if (!db)
{
NSLog(@"数据库打开失败!");
}
sqlite3_stmt *stmt=nil;
//添加数据到表
int result=sqlite3_prepare(db,[TJLEAFLETSDATAUTF8String], -1, &stmt,nil);
if (result==SQLITE_OK)
{
//给问号赋值1,2,3,表示第几个问号
if (name.length>0) {
sqlite3_bind_text(stmt, 1, [name UTF8String], -1,nil);
}else{
sqlite3_bind_text(stmt, 1, [@"100" UTF8String], -1, nil);
}
if (taskId.length>0) {
sqlite3_bind_text(stmt, 2, [taskId UTF8String], -1,nil);
}else{
sqlite3_bind_text(stmt, 2, [@"优点尚"UTF8String], -1,nil);
}
if (jifen.length>0) {
sqlite3_bind_text(stmt, 3, [jifen UTF8String], -1,nil);
}else{
sqlite3_bind_text(stmt, 3, [@"100" UTF8String], -1, nil);
}
if (keyWord.length>0) {
sqlite3_bind_text(stmt, 4, [keyWord UTF8String], -1,nil);
}else{
sqlite3_bind_text(stmt, 4, [@"100" UTF8String], -1, nil);
}
if (urlStr.length>0) {
sqlite3_bind_text(stmt, 5, [urlStr UTF8String], -1,nil);
}else{
sqlite3_bind_text(stmt, 5, [@"100" UTF8String], -1, nil);
}
}
if (sqlite3_step(stmt)==SQLITE_DONE)//是程序数据库运行一步!(执行完成)
{
NSLog(@"添加成功!");
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}
//刷单记录
+(BOOL)cunBrushName:(NSString *)name andtaskId:(NSString *)taskId andJifen:(NSString *)jifen andUrl:(NSString *)urlStr
{
[MyDatachuangJianTable:BRUSH];
sqlite3_open([[MyDatafilePath] UTF8String], &db);
if (!db)
{
NSLog(@"数据库打开失败!");
}
sqlite3_stmt *stmt=nil;
//添加数据到表
int result=sqlite3_prepare(db,[TJSJBRUSHUTF8String], -1, &stmt,nil);
if (result==SQLITE_OK)
{
//给问号赋值1,2,3,表示第几个问号
if (name.length>0) {
sqlite3_bind_text(stmt, 1, [name UTF8String], -1,nil);
}else{
sqlite3_bind_text(stmt, 1, [@"100" UTF8String], -1, nil);
}
if (taskId.length>0) {
sqlite3_bind_text(stmt, 2, [taskId UTF8String], -1,nil);
}else{
sqlite3_bind_text(stmt, 2, [@"你镔哥哥"UTF8String], -1,nil);
}
if (jifen.length>0) {
sqlite3_bind_text(stmt, 3, [jifen UTF8String], -1,nil);
}else{
sqlite3_bind_text(stmt, 3, [@"100" UTF8String], -1, nil);
}
if (urlStr.length>0) {
sqlite3_bind_text(stmt, 4, [urlStr UTF8String], -1,nil);
}else{
sqlite3_bind_text(stmt, 4, [@"100" UTF8String], -1, nil);
}
}
if (sqlite3_step(stmt)==SQLITE_DONE)//是程序数据库运行一步!(执行完成)
{
NSLog(@"添加成功!");
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}
//存取分享(名字、标题)
+(BOOL)cunShareDataOfName:(NSString *)name andString:(NSString *)title
{
[MyDatachuangJianTable:SHAREDATA];
sqlite3_open([[MyDatafilePath] UTF8String], &db);
if (!db)
{
NSLog(@"数据库打开失败!");
}
sqlite3_stmt *stmt=nil;
//添加数据到订单表
int result=sqlite3_prepare(db,[TJSJSHAREDATAUTF8String], -1, &stmt,nil);
if (result==SQLITE_OK)//
{
//给问号赋值1,2,3,表示第几个问号
if (name.length>0) {
sqlite3_bind_text(stmt, 1, [name UTF8String], -1,nil);
}else{
sqlite3_bind_text(stmt, 1, [@"100" UTF8String], -1, nil);
}
if (title.length>0) {
sqlite3_bind_text(stmt, 2, [title UTF8String], -1,nil);
}else{
sqlite3_bind_text(stmt, 2, [@"你镔哥哥"UTF8String], -1,nil);
}
}
if (sqlite3_step(stmt)==SQLITE_DONE)//是程序数据库运行一步!(执行完毕)
{
NSLog(@"添加成功!");
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}
+(BOOL)cunJobDateOfName:(NSString *)name andString:(NSString *)title andTTString:(NSString *)text andtaskId:(NSString *)taskId
{
[MyDatachuangJianTable:JOBDATA];
sqlite3_open([[MyDatafilePath] UTF8String], &db);
if (!db)
{
NSLog(@"数据库打开失败!");
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare(db,[TJSJJOBDATAUTF8String], -1, &stmt,nil);
if (result==SQLITE_OK)
{
//给问号赋值1,2,3,表示第几个问号
if (name.length>0) {
sqlite3_bind_text(stmt, 1, [name UTF8String], -1,nil);
}else{
sqlite3_bind_text(stmt, 1, [@"100" UTF8String], -1, nil);
}
if (title.length>0) {
sqlite3_bind_text(stmt, 2, [title UTF8String], -1,nil);
}else{
sqlite3_bind_text(stmt, 2, [@"你头哥"UTF8String], -1,nil);
}
if (text.length>0) {
sqlite3_bind_text(stmt, 3, [text UTF8String], -1,nil);
}else{
sqlite3_bind_text(stmt, 3, [@"你头哥"UTF8String], -1,nil);
}
if (taskId.length>0) {
sqlite3_bind_text(stmt, 4, [taskId UTF8String], -1,nil);
}else{
sqlite3_bind_text(stmt, 4, [@"你头哥"UTF8String], -1,nil);
}
}
if (sqlite3_step(stmt)==SQLITE_DONE)//是程序数据库运行一步!
{
NSLog(@"添加成功!");
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}
+(NSMutableArray *)quMappingData
{
NSMutableArray *arr=[[NSMutableArrayalloc]init];
//打开数据库
sqlite3_open([[MyDatafilePath] UTF8String], &db);
if (db==nil)
{
NSLog(@"数据库打开失败");
return arr;
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare_v2(db, [DQSJMAPPINGDATAUTF8String], -1, &stmt,nil);
if (result==SQLITE_OK)
{
while (sqlite3_step(stmt)==SQLITE_ROW)
{
char *name=(char *)sqlite3_column_text(stmt,0);
char *title=(char *)sqlite3_column_text(stmt,1);
NSMutableDictionary *dic=[[NSMutableDictionaryalloc]init];
[dic setObject:[NSStringstringWithCString:name encoding:NSUTF8StringEncoding]forKey:@"name"];
[dic setObject:[NSStringstringWithCString:title encoding:NSUTF8StringEncoding]forKey:@"title"];
[arr addObject:dic];
}
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return arr;
}
+(NSMutableArray *)quBrushData
{
NSMutableArray *arr=[[NSMutableArrayalloc]init];
//打开数据库
sqlite3_open([[MyDatafilePath] UTF8String], &db);
if (db==nil)
{
NSLog(@"数据库打开失败");
return arr;
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare_v2(db, [DQSJBRUSHUTF8String], -1, &stmt,nil);
if (result==SQLITE_OK)
{
while (sqlite3_step(stmt)==SQLITE_ROW)
{
char *name=(char *)sqlite3_column_text(stmt,0);
char *taskid=(char *)sqlite3_column_text(stmt,1);
char *jifen=(char *)sqlite3_column_text(stmt,2);
char *url=(char *)sqlite3_column_text(stmt,3);
NSMutableDictionary *dic=[[NSMutableDictionaryalloc]init];
[dic setObject:[NSStringstringWithCString:name encoding:NSUTF8StringEncoding]forKey:@"name"];
[dic setObject:[NSStringstringWithCString:taskid encoding:NSUTF8StringEncoding]forKey:@"taskid"];
[dic setObject:[NSStringstringWithCString:jifen encoding:NSUTF8StringEncoding]forKey:@"jifen"];
[dic setObject:[NSStringstringWithCString:url encoding:NSUTF8StringEncoding]forKey:@"url"];
[arr addObject:dic];
}
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return arr;
}
+(NSMutableArray *)quShareData
{
NSMutableArray *arr=[[NSMutableArrayalloc]init];
//打开数据库
sqlite3_open([[MyDatafilePath] UTF8String], &db);
if (db==nil)
{
NSLog(@"数据库打开失败");
return arr;
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare_v2(db, [DQSJSHAREDATAUTF8String], -1, &stmt,nil);
if (result==SQLITE_OK)
{
while (sqlite3_step(stmt)==SQLITE_ROW)
{
char *name=(char *)sqlite3_column_text(stmt,0);
char *title=(char *)sqlite3_column_text(stmt,1);
NSMutableDictionary *dic=[[NSMutableDictionaryalloc]init];
[dic setObject:[NSStringstringWithCString:name encoding:NSUTF8StringEncoding]forKey:@"name"];
[dic setObject:[NSStringstringWithCString:title encoding:NSUTF8StringEncoding]forKey:@"title"];
[arr addObject:dic];
}
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return arr;
}
+(NSMutableArray *)quJobData
{
NSMutableArray *arr=[[NSMutableArrayalloc]init];
//打开数据库
sqlite3_open([[MyDatafilePath] UTF8String], &db);
if (db==nil)
{
NSLog(@"数据库打开失败");
return arr;
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare_v2(db, [DQLEAFLETSDATA UTF8String], -1, &stmt,nil);
if (result==SQLITE_OK)
{
while (sqlite3_step(stmt)==SQLITE_ROW)
{
char *name=(char *)sqlite3_column_text(stmt,0);
char *title=(char *)sqlite3_column_text(stmt,1);
char *text=(char *)sqlite3_column_text(stmt,2);
char *taskId=(char *)sqlite3_column_text(stmt,3);
NSMutableDictionary *dic=[[NSMutableDictionaryalloc]init];
[dic setObject:[NSStringstringWithCString:name encoding:NSUTF8StringEncoding]forKey:@"name"];
[dic setObject:[NSStringstringWithCString:title encoding:NSUTF8StringEncoding]forKey:@"title"];
[dic setObject:[NSStringstringWithCString:text encoding:NSUTF8StringEncoding]forKey:@"text"];
[dic setObject:[NSStringstringWithCString:taskId encoding:NSUTF8StringEncoding]forKey:@"taskId"];
[arr addObject:dic];
}
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return arr;
}
+(NSMutableArray *)quLeafData
{
NSMutableArray *arr=[[NSMutableArrayalloc]init];
//打开数据库
sqlite3_open([[MyDatafilePath] UTF8String], &db);
if (db==nil)
{
NSLog(@"数据库打开失败");
return arr;
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare_v2(db, [DQLEAFLETSDATAUTF8String], -1, &stmt,nil);
if (result==SQLITE_OK)
{
//name,taskid,jifen,keyword,url
while (sqlite3_step(stmt)==SQLITE_ROW)
{
char *name=(char *)sqlite3_column_text(stmt,0);
char *taskid=(char *)sqlite3_column_text(stmt,1);
char *jifen=(char *)sqlite3_column_text(stmt,2);
char *url=(char *)sqlite3_column_text(stmt,3);
NSMutableDictionary *dic=[[NSMutableDictionaryalloc]init];
[dic setObject:[NSStringstringWithCString:name encoding:NSUTF8StringEncoding]forKey:@"name"];
[dic setObject:[NSStringstringWithCString:taskid encoding:NSUTF8StringEncoding]forKey:@"taskid"];
[dic setObject:[NSStringstringWithCString:jifen encoding:NSUTF8StringEncoding]forKey:@"jifen"];
[dic setObject:[NSStringstringWithCString:jifen encoding:NSUTF8StringEncoding]forKey:@"keyword"];
[dic setObject:[NSStringstringWithCString:jifen encoding:NSUTF8StringEncoding]forKey:@"taskOptCourse"];
[dic setObject:[NSStringstringWithCString:url encoding:NSUTF8StringEncoding]forKey:@"url"];
[arr addObject:dic];
}
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return arr;
}
+(BOOL)shanMappingData
{
sqlite3_open([[MyDatafilePath] UTF8String], &db);
if (!db)
{
NSLog(@"数据库打开失败!");
return NO;
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare_v2(db,[SCSJMAPPINGDATAUTF8String], -1, &stmt,nil);
if (result==SQLITE_OK)
{
if (sqlite3_step(stmt)==SQLITE_DONE)//是程序数据库运行一步!
{
NSLog(@"删除成功!");
}
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}
+(BOOL)shanBrushData
{
sqlite3_open([[MyDatafilePath] UTF8String], &db);
if (!db)
{
NSLog(@"数据库打开失败!");
return NO;
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare_v2(db,[SCSJMAPPINGDATAUTF8String], -1, &stmt,nil);
if (result==SQLITE_OK)
{
if (sqlite3_step(stmt)==SQLITE_DONE)//是程序数据库运行一步!
{
NSLog(@"删除成功!");
}
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}
+(BOOL)shanShareData
{
sqlite3_open([[MyDatafilePath] UTF8String], &db);
if (!db)
{
NSLog(@"数据库打开失败!");
return NO;
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare_v2(db,[SCSJBRUSHUTF8String], -1, &stmt,nil);
if (result==SQLITE_OK)
{
if (sqlite3_step(stmt)==SQLITE_DONE)//是程序数据库运行一步!
{
NSLog(@"删除成功!");
}
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}
+(BOOL)shanJobData
{
sqlite3_open([[MyDatafilePath] UTF8String], &db);
if (!db)
{
NSLog(@"数据库打开失败!");
return NO;
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare_v2(db,[SCSJJOBDATAUTF8String], -1, &stmt,nil);
if (result==SQLITE_OK)
{
if (sqlite3_step(stmt)==SQLITE_DONE)//是程序数据库运行一步!
{
NSLog(@"删除成功!");
}
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}
+(BOOL)shanLeafData
{
sqlite3_open([[MyDatafilePath] UTF8String], &db);
if (!db)
{
NSLog(@"数据库打开失败!");
return NO;
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare_v2(db,[SCSJLEAFLETSDATAUTF8String], -1, &stmt,nil);
if (result==SQLITE_OK)
{
if (sqlite3_step(stmt)==SQLITE_DONE)//是程序数据库运行一步!
{
NSLog(@"删除成功!");
}
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}
@end
iOS基础8:自定义MyData/自定义SQLite用于网络判断,版本判断,图片缓存处理,下载或者上传的GET或POST请求,加密手段,.数据解析