标签:sqlite 版本判断 图片缓存处理 下载或者上传的get或post请求 加密手段
镔哥,这篇文章是用自己的工程项目来的,主要是代码为主,但是会有注释,让大家能更好理解,让大家做工程更多一个选择,这其实就是自己自定义SQLite,不多说,见代码例子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 = [[[[[UIDevice currentDevice] 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=[NSFileManager defaultManager];//文件管理器(处理文件分配、保存,读取)
//判读文件路径是否存在
if ([fm fileExistsAtPath:path]==NO)
{
//就创建文件路径
[fm createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
}
return path;
}
+(NSString *)picturesName:(NSString *)path//利用图片的url生成图片的名称:
{
if ([path hasSuffix:@".bmp"]||[path hasSuffix:@".jpg"]||[path hasSuffix:@".tiff"]||[path hasSuffix:@".gif"]||[path hasSuffix:@".pcx"]||[path hasSuffix:@".png"]||[path hasSuffix:@".jpeg"])
{
NSMutableString *str=[NSMutableString stringWithString:path];
for (int i=path.length-1; i>=0; i--)
{
if ([str characterAtIndex:i]==‘/‘) {
[str deleteCharactersInRange:NSMakeRange(i, 1)];
}
}
return str;
}
else
{
NSMutableString *str=[NSMutableString stringWithString:[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=[NSFileManager defaultManager];//定义文件
NSString *pp=[MyData picturePath];
NSString *lujing=[pp stringByAppendingPathComponent:[MyData picturesName:path]];//创建文件路径
NSData *data=UIImagePNGRepresentation(image);//将图片转换为NSData格式
BOOL flay=[file createFileAtPath:lujing contents:data attributes:nil];//创建文件
return flay;
}
+(BOOL)judgeIsImage:(NSString *)path
{
NSString *str=[MyData picturesName:path];
NSString *str_1=[MyData picturePath];
NSString *string=[str_1 stringByAppendingPathComponent:str];
NSFileManager *manager=[NSFileManager defaultManager];
if ([manager fileExistsAtPath:string]==YES)
{
return YES;
}
else
{
return NO;
}
}
+(UIImage *)obtainImage:(NSString *)path
{
NSFileManager *file=[NSFileManager defaultManager];//定义文件
NSString *pp=[MyData picturePath];
NSString *lujing=[pp stringByAppendingPathComponent:[MyData picturesName:path]];//创建文件路径
NSData *data=[file contentsAtPath:lujing];
UIImage *image=[UIImage imageWithData:data];
return image;
}
+(NSString *)huoPathString:(NSString *)string
{
NSString *pp=[MyData picturePath];
return [pp stringByAppendingPathComponent:[MyData picturesName:string]];//创建文件路径
}
+(BOOL)RemoveArrPictures
{
NSError *error=nil;
NSString *path=[MyData picturePath];
NSFileManager *fileManager=[NSFileManager defaultManager];
[fileManager removeItemAtPath:path error:&error];
return YES;
}
//md5加密***************************************************************
+(NSString *)md5:(NSString *)str
{
const char *cStr = [str UTF8String];
unsigned char result[32];
CC_MD5( cStr, strlen(cStr), result );
return [NSString stringWithFormat:
@"%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=[NSURL URLWithString:urlStr];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
connection=[NSURLConnection connectionWithRequest: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.delegate respondsToSelector:@selector(sendData:andProgress:andFilg:andIndexPath:andError:)]) {
[self.delegate sendData:nil andProgress:0 andFilg:@"访问超时" andIndexPath:nil andError:YES];
}
if ([self.delegate respondsToSelector:@selector(sendData:andProgress:andFilg:andError:)]) {
[self.delegate sendData:nil andProgress:0 andFilg:@"访问超时" andError:YES];
}
if ([self.delegate respondsToSelector:@selector(sendData:andFilg:andIndexPath:andError:)]) {
[self.delegate sendData:nil andFilg:@"访问超时" andIndexPath:self.indexPath andError:YES];
}
if ([self.delegate respondsToSelector:@selector(sendData:andFilg:andError:)]) {
[self.delegate sendData:nil andFilg:@"访问超时" andError:YES];
}
[connection cancel];//停止下载
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{//将要下载时执行
receiveData=[[NSMutableData alloc]initWithCapacity:0];
AllLength=[response expectedContentLength];
urlstr=[[response URL]absoluteString];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{//正在下载时执行
[receiveData appendData:data];
long long currentDataLength=[receiveData length];
float proportion=(float)currentDataLength/(float)AllLength;
if ([self.delegate respondsToSelector:@selector(sendData:andProgress:andFilg:andIndexPath:andError:)]) {
[self.delegate sendData:receiveData andProgress:proportion andFilg:urlstr andIndexPath:self.indexPath andError:NO];
}
if ([self.delegate respondsToSelector:@selector(sendData:andProgress:andFilg:andError:)]) {
[self.delegate sendData:receiveData andProgress:proportion andFilg:urlstr andError:NO];
}
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{//下载完成时执行
NSLog(@"3333333333333333");
if ([self.delegate respondsToSelector:@selector(sendData:andProgress:andFilg:andIndexPath:andError:)]) {
[self.delegate sendData:receiveData andProgress:1 andFilg:urlstr andIndexPath:nil andError:NO];
}
if ([self.delegate respondsToSelector:@selector(sendData:andProgress:andFilg:andError:)]) {
[self.delegate sendData:receiveData andProgress:1 andFilg:urlstr andError:NO];
}
if ([self.delegate respondsToSelector:@selector(sendData:andFilg:andIndexPath:andError:)]) {
[self.delegate sendData:receiveData andFilg:urlstr andIndexPath:self.indexPath andError:NO];
}
if ([self.delegate respondsToSelector:@selector(sendData:andFilg:andError:)]) {
[self.delegate sendData:receiveData andFilg:urlstr andError:NO];
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{//错误时!!!!!!!!!!!!!
NSLog(@"444444444444444");
if ([self.delegate respondsToSelector:@selector(sendData:andProgress:andFilg:andIndexPath:andError:)]) {
[self.delegate sendData:nil andProgress:0 andFilg:@"访问超时" andIndexPath:nil andError:YES];
}
if ([self.delegate respondsToSelector:@selector(sendData:andProgress:andFilg:andError:)]) {
[self.delegate sendData:nil andProgress:0 andFilg:@"访问超时" andError:YES];
}
if ([self.delegate respondsToSelector:@selector(sendData:andFilg:andIndexPath:andError:)]) {
[self.delegate sendData:nil andFilg:@"访问超时" andIndexPath:self.indexPath andError:YES];
}
if ([self.delegate respondsToSelector:@selector(sendData:andFilg:andError:)]) {
[self.delegate sendData:nil andFilg:@"访问超时" andError:YES];
}
}
//Post
//网络判断*******************************************************************************
+(BOOL)determineNetworkStatus
{
BOOL flay;
Reachability *r=[Reachability reachabilityForInternetConnection];
switch ([r currentReachabilityStatus]) {
case NotReachable:
flay=NO;
break;
case ReachableViaWiFi:
flay=YES;
break;
case ReachableViaWWAN:
flay=YES;
break;
default:
break;
}
if (!flay) {
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"没有检测到网络" delegate:self cancelButtonTitle:@"知道了~" otherButtonTitles:nil];
[alert show];
}
return flay;
}
//POST请求****************************************************************************
-(void)postUrl:(NSString *)url andString:(NSString *)string
{
// NSLog(@"4444444444444");
NSMutableData *postData=[[NSMutableData alloc]init];
[postData appendData:[string dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
connection=[NSURLConnection connectionWithRequest: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=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
[array setArray:arr];
//方法二:(第三方提供方法“JSON.h”)
NSString *str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
[array setArray:[str JSONValue]];
}
+(void)xmlFor:(NSMutableArray *)array toIn:(NSData *)data
{
[array removeAllObjects];
NSError *error=nil;
GDataXMLDocument *document=[[GDataXMLDocument alloc]initWithData:data options:0 error:&error];
GDataXMLElement *element=[document rootElement];
NSArray *eArray=[element elementsForName:@"student"];
for (GDataXMLElement *e in eArray) {
NSMutableDictionary *dic=[[NSMutableDictionary alloc]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 = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:filePath]){
return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
}
return 0;
}
+(float)folderSizeAtPath
{
NSFileManager* manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:[MyData picturePath]])
{
return 0;
}
NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:[MyData picturePath]] objectEnumerator];
NSString* fileName;
long long folderSize = 0;
while ((fileName = [childFilesEnumerator nextObject]) != nil){
NSString* fileAbsolutePath = [[MyData picturePath] 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=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=[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 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:10];
//分界线 --AaB03x
NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
//结束符 AaB03x--
NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
NSData* data;
if(image){
//判断图片是不是png格式的文件
if (UIImagePNGRepresentation(image)) {
//返回为png图像。
NSLog(@"返回png");
// data = UIImagePNGRepresentation(image);
data = UIImageJPEGRepresentation(image, 0.1);
}else {
//返回为JPEG图像。
NSLog(@"返回jpeg");
data = UIImageJPEGRepresentation(image, 0.1);
}
}
NSLog(@"---------%d",data.length);
//http body的字符串
NSMutableString *body=[[NSMutableString alloc]init];
//参数的集合的所有key的集合
NSArray *keys= [postParems allKeys];
//遍历keys
for(int i=0;i<[keys count];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",[postParems objectForKey:key]];
NSLog(@"添加字段的值==%@",[postParems objectForKey: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=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
//声明myRequestData,用来放入http body
NSMutableData *myRequestData=[NSMutableData data];
//将body字符串转化为UTF8格式的二进制
[myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
if(image){
//将image的data加入
[myRequestData appendData:data];
}
//加入结束符--AaB03x--
[myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
//设置HTTPHeader中Content-Type的值
NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
//设置HTTPHeader
[request setValue:content forHTTPHeaderField:@"Content-Type"];
//设置Content-Length
[request setValue:[NSString stringWithFormat:@"%d", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];
//设置http body
[request setHTTPBody:myRequestData];
//http method
[request setHTTPMethod:@"POST"];
NSHTTPURLResponse *urlResponese = nil;
NSError *error = [[NSError alloc]init];
NSData* resultData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponese error:&error];
NSString* result= [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
NSLog(@"%@",result);
NSLog(@"%d",[urlResponese statusCode]);
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([[MyData filePath] UTF8String], &db);
if(!db)
{
NSLog(@"数据库打开失败!");
return NO;
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare_v2(db, [string UTF8String], -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
{
[MyData chuangJianTable:MAPPINGDATA];
sqlite3_open([[MyData filePath] UTF8String], &db);
if (!db)
{
NSLog(@"数据库打开失败!");
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare(db,[TJSJMAPPINGDATA UTF8String], -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
{
[MyData chuangJianTable:chuandanURL];
sqlite3_open([[MyData filePath] UTF8String], &db);
if (!db)
{
NSLog(@"数据库打开失败!");
}
sqlite3_stmt *stmt=nil;
//添加数据到表
int result=sqlite3_prepare(db,[TJLEAFLETSDATA UTF8String], -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
{
[MyData chuangJianTable:BRUSH];
sqlite3_open([[MyData filePath] UTF8String], &db);
if (!db)
{
NSLog(@"数据库打开失败!");
}
sqlite3_stmt *stmt=nil;
//添加数据到表
int result=sqlite3_prepare(db,[TJSJBRUSH UTF8String], -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
{
[MyData chuangJianTable:SHAREDATA];
sqlite3_open([[MyData filePath] UTF8String], &db);
if (!db)
{
NSLog(@"数据库打开失败!");
}
sqlite3_stmt *stmt=nil;
//添加数据到订单表
int result=sqlite3_prepare(db,[TJSJSHAREDATA UTF8String], -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
{
[MyData chuangJianTable:JOBDATA];
sqlite3_open([[MyData filePath] UTF8String], &db);
if (!db)
{
NSLog(@"数据库打开失败!");
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare(db,[TJSJJOBDATA UTF8String], -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=[[NSMutableArray alloc]init];
//打开数据库
sqlite3_open([[MyData filePath] UTF8String], &db);
if (db==nil)
{
NSLog(@"数据库打开失败");
return arr;
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare_v2(db, [DQSJMAPPINGDATA 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);
NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
[dic setObject:[NSString stringWithCString:name encoding:NSUTF8StringEncoding] forKey:@"name"];
[dic setObject:[NSString stringWithCString:title encoding:NSUTF8StringEncoding] forKey:@"title"];
[arr addObject:dic];
}
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return arr;
}
+(NSMutableArray *)quBrushData
{
NSMutableArray *arr=[[NSMutableArray alloc]init];
//打开数据库
sqlite3_open([[MyData filePath] UTF8String], &db);
if (db==nil)
{
NSLog(@"数据库打开失败");
return arr;
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare_v2(db, [DQSJBRUSH UTF8String], -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=[[NSMutableDictionary alloc]init];
[dic setObject:[NSString stringWithCString:name encoding:NSUTF8StringEncoding] forKey:@"name"];
[dic setObject:[NSString stringWithCString:taskid encoding:NSUTF8StringEncoding] forKey:@"taskid"];
[dic setObject:[NSString stringWithCString:jifen encoding:NSUTF8StringEncoding] forKey:@"jifen"];
[dic setObject:[NSString stringWithCString:url encoding:NSUTF8StringEncoding] forKey:@"url"];
[arr addObject:dic];
}
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return arr;
}
+(NSMutableArray *)quShareData
{
NSMutableArray *arr=[[NSMutableArray alloc]init];
//打开数据库
sqlite3_open([[MyData filePath] UTF8String], &db);
if (db==nil)
{
NSLog(@"数据库打开失败");
return arr;
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare_v2(db, [DQSJSHAREDATA 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);
NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
[dic setObject:[NSString stringWithCString:name encoding:NSUTF8StringEncoding] forKey:@"name"];
[dic setObject:[NSString stringWithCString:title encoding:NSUTF8StringEncoding] forKey:@"title"];
[arr addObject:dic];
}
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return arr;
}
+(NSMutableArray *)quJobData
{
NSMutableArray *arr=[[NSMutableArray alloc]init];
//打开数据库
sqlite3_open([[MyData filePath] 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=[[NSMutableDictionary alloc]init];
[dic setObject:[NSString stringWithCString:name encoding:NSUTF8StringEncoding] forKey:@"name"];
[dic setObject:[NSString stringWithCString:title encoding:NSUTF8StringEncoding] forKey:@"title"];
[dic setObject:[NSString stringWithCString:text encoding:NSUTF8StringEncoding] forKey:@"text"];
[dic setObject:[NSString stringWithCString:taskId encoding:NSUTF8StringEncoding] forKey:@"taskId"];
[arr addObject:dic];
}
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return arr;
}
+(NSMutableArray *)quLeafData
{
NSMutableArray *arr=[[NSMutableArray alloc]init];
//打开数据库
sqlite3_open([[MyData filePath] 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)
{
//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=[[NSMutableDictionary alloc]init];
[dic setObject:[NSString stringWithCString:name encoding:NSUTF8StringEncoding] forKey:@"name"];
[dic setObject:[NSString stringWithCString:taskid encoding:NSUTF8StringEncoding] forKey:@"taskid"];
[dic setObject:[NSString stringWithCString:jifen encoding:NSUTF8StringEncoding] forKey:@"jifen"];
[dic setObject:[NSString stringWithCString:jifen encoding:NSUTF8StringEncoding] forKey:@"keyword"];
[dic setObject:[NSString stringWithCString:jifen encoding:NSUTF8StringEncoding] forKey:@"taskOptCourse"];
[dic setObject:[NSString stringWithCString:url encoding:NSUTF8StringEncoding] forKey:@"url"];
[arr addObject:dic];
}
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return arr;
}
+(BOOL)shanMappingData
{
sqlite3_open([[MyData filePath] UTF8String], &db);
if (!db)
{
NSLog(@"数据库打开失败!");
return NO;
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare_v2(db,[SCSJMAPPINGDATA UTF8String], -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([[MyData filePath] UTF8String], &db);
if (!db)
{
NSLog(@"数据库打开失败!");
return NO;
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare_v2(db,[SCSJMAPPINGDATA UTF8String], -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([[MyData filePath] UTF8String], &db);
if (!db)
{
NSLog(@"数据库打开失败!");
return NO;
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare_v2(db,[SCSJBRUSH UTF8String], -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([[MyData filePath] UTF8String], &db);
if (!db)
{
NSLog(@"数据库打开失败!");
return NO;
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare_v2(db,[SCSJJOBDATA UTF8String], -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([[MyData filePath] UTF8String], &db);
if (!db)
{
NSLog(@"数据库打开失败!");
return NO;
}
sqlite3_stmt *stmt=nil;
int result=sqlite3_prepare_v2(db,[SCSJLEAFLETSDATA UTF8String], -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请求,加密手段,.数据解析
标签:sqlite 版本判断 图片缓存处理 下载或者上传的get或post请求 加密手段
原文地址:http://blog.csdn.net/sammyieveo/article/details/41520069