您的位置:首页 > 移动开发 > Objective-C

IOS   Objective c 同步 异步链接 …

2013-09-22 14:23 344 查看
1. Network.h

#import
<Foundation/Foundation.h>

@interface Network :
NSObject<NSURLConnectionDelegate>

@property
(nonatomic,retain)NSMutableData
* recivedata;

//同步链接

- (void)startC;

//异步链接

- (void)startA;

- (void)dealloc;

@end

2. Network.m
文件


 

#import "Network.h"

#import "“XMLReader”的副本.h"

@implementation Network

@synthesize
recivedata=_recivedata;

//- (void)startC

//{

//    //第一步:
创建URl

//NSURL *url=[NSURL URLWithString:@"http://api.hudong.com/iphonexml.do?type=focus-c"];

//    //第二步
创建请求

////    NSURLRequest *
request=[NSURLRequest requestWithURL:url]; 
//默认的是GET

//    NSMutableURLRequest *
request=[NSMutableURLRequest requestWithURL:url];

//    [request
setHTTPMethod:@"POST"];

//    //第三步
发送请求

//    NSURLResponse
*respnse=nil;

//    NSError *error=nil;

//    NSData *data
=[NSURLConnection sendSynchronousRequest:request
returningResponse:&respnse
error:&error];

//    NSString *
str=[[NSString alloc]initWithData:data
encoding:NSUTF8StringEncoding];

//    NSLog(@"%@",str);

//}

- (void)startA

{

   
//第一步: 创建URl

   
NSURL *url=[NSURL
URLWithString:@"http://api.hudong.com/iphonexml.do?type=focus-c"];

   
//第二步 创建请求

   
//    NSURLRequest *
request=[NSURLRequest requestWithURL:url]; 
//默认的是GET

   
NSMutableURLRequest * request=[NSMutableURLRequest
requestWithURL:url];

    [request
setHTTPMethod:@"POST"];

   
//第三步 发送请求

   
[NSURLConnection
connectionWithRequest:request
delegate:self];

    

}

//接受到服务器回应

- (void)connection:(NSURLConnection
*)connection didReceiveResponse:(NSURLResponse
*)response

{

   
NSLog(@"接受到服务器回应");

   
//self.recivedata  用autorelease

   
self.recivedata=[[[NSMutableData
alloc]init]autorelease];

}

//接受数据   n次运行

- (void)connection:(NSURLConnection
*)connection didReceiveData:(NSData *)data

{

   NSLog(@"接受数据");

   
[self.recivedata
appendData:data];

}

//错误方法

- (void)connection:(NSURLConnection
*)connection didFailWithError:(NSError *)error

{

   
NSLog(@"error %@",[error
localizedDescription]);

}

//成功接受

-
(void)connectionDidFinishLoading:(NSURLConnection
*)connection

{

   NSLog(@"成功接受");

     
  NSString *
str=[[NSString
alloc]initWithData:self.recivedata
encoding:NSUTF8StringEncoding];

   
//将字符串xml转为字典

   
NSDictionary *dic=[XMLReader
dictionaryForXMLString:str
error:nil];

    
 NSLog(@"%@",dic);

    [str
release];

   
//使用JSON     //

//    NSData *
jsonData=[NSJSONSerialization dataWithJSONObject:dic
options:NSJSONWritingPrettyPrinted error:nil];

//   
//将json的Data转为字典

//    NSDictionary
*jsonDic=[NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers error:nil];

//   
NSLog(@"%@",jsonDic); 

   
NSString * resultStr=[[[[[[dic
valueForKey:@"response"]
valueForKey:@"docList"]
valueForKey:@"docInfo"]
objectAtIndex:0]
valueForKey:@"docImg"]valueForKey:@"text"];

   NSLog(@"%@",resultStr);

}

- (void)dealloc

{

    [_recivedata
release];

   
[super autorelease];

}

@end

3.XMLReader”的副本.h

 

#import
<Foundation/Foundation.h>

@interface XMLReader : NSObject
<NSXMLParserDelegate>

{

   NSMutableArray *dictionaryStack;

   NSMutableString *textInProgress;

   NSError
**errorPointer;

}

+ (NSDictionary
*)dictionaryForXMLData:(NSData *)data
error:(NSError **)errorPointer;

+ (NSDictionary
*)dictionaryForXMLString:(NSString *)string
error:(NSError **)errorPointer;

@end

4.XMLReader”的副本.m

 

#import "“XMLReader”的副本.h"

NSString *const kXMLReaderTextNodeKey
= @"text";

@interface XMLReader (Internal)

- (id)initWithError:(NSError
**)error;

- (NSDictionary
*)objectWithData:(NSData *)data;

@end

@implementation XMLReader

#pragma mark -

#pragma mark Public methods

+ (NSDictionary
*)dictionaryForXMLData:(NSData *)data
error:(NSError **)error

{

   XMLReader
*reader = [[XMLReader alloc]
initWithError:error];

   NSDictionary
*rootDictionary = [reader objectWithData:data];

    [reader
release];

   return
rootDictionary;

}

+ (NSDictionary
*)dictionaryForXMLString:(NSString *)string
error:(NSError **)error

{

   
NSData *data = [string
dataUsingEncoding:NSUTF8StringEncoding];

   
return [XMLReader
dictionaryForXMLData:data
error:error];

}

#pragma mark -

#pragma mark Parsing

- (id)initWithError:(NSError
**)error

{

   if
(self = [super init])

    {

     
 errorPointer = error;

    }

    return
self;

}

- (void)dealloc

{

   
[dictionaryStack release];

   
[textInProgress release];

    [super
dealloc];

}

- (NSDictionary
*)objectWithData:(NSData *)data

{

    // Clear out
any old data

   
[dictionaryStack release];

   
[textInProgress release];

    

   
dictionaryStack = [[NSMutableArray
alloc]
init];

   
textInProgress = [[NSMutableString
alloc]
init];

    

    // Initialize
the stack with a fresh dictionary

   
[dictionaryStack
addObject:[NSMutableDictionary
dictionary]];

    

    // Parse the
XML

   NSXMLParser
*parser = [[NSXMLParser alloc]
initWithData:data];

   
parser.delegate = self;

   BOOL success
= [parser parse];

    

    // Return the
stack's root dictionary on success

   if
(success)

    {

     
 NSDictionary *resultDict =
[dictionaryStack
objectAtIndex:0];

     
 return resultDict;

    }

    

    return
nil;

}

#pragma mark -

#pragma mark NSXMLParserDelegate methods

- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict

{

    // Get the
dictionary for the current level in the stack

   NSMutableDictionary *parentDict =
[dictionaryStack lastObject];

    // Create the
child dictionary for the new element, and initilaize it with the
attributes

   
NSMutableDictionary *childDict = [NSMutableDictionary
dictionary];

    [childDict
addEntriesFromDictionary:attributeDict];

    

    // If there's
already an item for this key, it means we need to create an
array

   id
existingValue = [parentDict
objectForKey:elementName];

   if
(existingValue)

    {

     
 NSMutableArray *array =
nil;

     
 if ([existingValue
isKindOfClass:[NSMutableArray
class]])

     
  {

     
      //
The array exists, so use it

     
      array =
(NSMutableArray *) existingValue;

     
  }

     
 else

     
  {

     
      //
Create an array if it doesn't exist

     
      array =
[NSMutableArray array];

     
      [array
addObject:existingValue];

     
      //
Replace the child dictionary with an array of children
dictionaries

     
     
[parentDict setObject:array
forKey:elementName];

     
  }

    
   

     
  // Add the new child dictionary to the
array

     
  [array addObject:childDict];

    }

   else

    {

     
  // No existing value, so update the
dictionary

     
  [parentDict setObject:childDict
forKey:elementName];

    }

    

    // Update the
stack

   
[dictionaryStack
addObject:childDict];

}

- (void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName

{

    // Update the
parent dict with text info

   NSMutableDictionary *dictInProgress =
[dictionaryStack lastObject];

    

    // Set the
text property

   
if ([textInProgress
length] >
0)

    {

     
  [dictInProgress
setObject:textInProgress
forKey:kXMLReaderTextNodeKey];

     
  // Reset the text

     
  [textInProgress
release];

     
 textInProgress =
[[NSMutableString alloc]
init];

    }

    

    // Pop the
current dict

   
[dictionaryStack
removeLastObject];

}

- (void)parser:(NSXMLParser *)parser
foundCharacters:(NSString *)string

{

    // Build the
text value

   
[textInProgress appendString:string];

}

- (void)parser:(NSXMLParser *)parser
parseErrorOccurred:(NSError *)parseError

{

    // Set the
error pointer to the parser's error object

    *errorPointer
= parseError;

}

@end

5.main

 

#import
<Foundation/Foundation.h>

#import "Network.h"

#define kFILEPATH
@"/Users/ibokan/Desktop/MyFile"

#define rFILEPATH @"/Users/ibokan/Desktop/123"

int main (int argc, const
char * argv[])

{

   
@autoreleasepool { 

    
   

     
 Network
*network=[[Network
alloc]init];

     
  [network startA];

    
   

    
   

    
   

    
   

//     
  //编译的时候

// //      
NSLog(@"%@",[NSBundle mainBundle]);

//      
 

//     
  //创建文件管理器: 创建 移动 删除 读取

//     
  NSFileManager * filemanage=[NSFileManager
defaultManager];//单例模式

//      
 

//     
  NSError *error=nil;

//     
  //查看文件下的目录

//     
  NSArray *fileArray=[filemanage
contentsOfDirectoryAtPath:kFILEPATH
error:&error];

//     
  if(!error)  
//查看路径下的东西

//     
  {

//     
     
NSLog(@"%@",fileArray);

//     
  }

//     
  //补齐路径 

//      
 

//     
  NSString * myfilePath=[NSString
stringWithFormat:@"%@/save01.txt",kFILEPATH];

//     
  //临时路径

//       //
NSString * myfilePath2=[NSString
stringWithFormat:@"%@/123.txt",rFILEPATH];

//     
  //查看路径是是否有文件存在

//     
  if([filemanage fileExistsAtPath:myfilePath])

//     
  {

//     
     
//如果有 则读取文件

//     
     

//     
      NSString
*rFileInfo=[NSString stringWithContentsOfFile:myfilePath
encoding:NSUTF8StringEncoding error:nil];

//     
     
NSLog(@"【通过读取的内容】:%@",rFileInfo);

//      
     

//     
     

//     
      NSData
*rData=[NSData
dataWithContentsOfFile:myfilePath];//数据流

//     
     
NSLog(@"【通过NSData读取的内容】:%@",rData);

//     
     
//将数据转换成字符串

//     
      NSString *
rDataStr=[[NSString alloc]initWithData:rData
encoding:NSUTF8StringEncoding];

//     
     
NSLog(@"【转换后的rData内容】:%@",rDataStr);

//     
      [rDataStr
release];

//      
     //
     
     

//     
     
//移出文件

////      
    BOOL resu= [filemanage
removeItemAtPath:myfilePath error:nil];

////     
     
if(resu)

////     
      {

////     
     
   
NSLog(@"移出成功");

////     
      }

////     
      else

////     
      {

////     
     
   
NSLog(@"移出失败");

////     
      }

//     
     
//移动文件

////      
    BOOL ress= [filemanage
moveItemAtPath:myfilePath toPath:myfilePath2 error:nil];

////     
     
if(ress)

////     
      {

////     
     
   
NSLog(@"移动成功");

////     
      }

////     
      else

////     
      {

////     
     
   
NSLog(@"移动失败");

////     
      }

//      
     

//     
     
//复制文件

////     
      BOOL
rees=[filemanage copyItemAtPath:myfilePath toPath:myfilePath2
error:nil];

////     
     
if(rees)

////      
      {

////      
     
   
NSLog(@"复制成功");

////      
      }

////     
      else

////     
      {

////     
     
   
NSLog(@"复制失败");

////     
      }

//

//     
  }

//     
  else

//     
  {

//     
     
//如果没有 则创建文件

//      
     

//     
     
//为下面的DAta 是数据 然后把它转为NSDATA
就oK

//     
      NSString *
myfileInfo=@"奥运会快结束了1!";

//     
      NSData
*myfileDate=[myfileInfo
dataUsingEncoding:NSUTF8StringEncoding];//创建数据 把上边的字符串  
NSUTF8StringEncoding转

//     
     
//创建文件

//     
      BOOL
result= [filemanage createFileAtPath:myfilePath contents:myfileDate
attributes:nil];

//     
     
if(result)

//     
      {

//     
     
   
NSLog(@"创建成功");

//     
      }

//     
      else

//     
      {

//     
     
   
NSLog(@"创建失败");

//     
      }

//      
     

//     
  }  

//      
 

////     
  NSOutputStream *outStream=[NSOutputStream
outputStreamToFileAtPath:kFILEPATH append:YES];

////     
  NSString *string
=@"我是输出流,我写的这句话";

////     
  [outStream open];

////     
  NSData *data=[NSData

//      
 

//      
 

//      
 

//      
 

//     
 

//     
  NSInputStream * inputStream=[NSInputStream
inputStreamWithFileAtPath:myfilePath];

//     
  [inputStream open]; 
//打开流

//     
  //buffer 从哪里开始读  读多少

//     
  uint8 buffer[1000];

//     
  int length=(int)[inputStream read:buffer
maxLength:1000];

//     
  NSString * info=[[NSString
alloc]initWithBytes:buffer length:length
encoding:NSUTF8StringEncoding];

//     
  NSLog(@"【输入流读取的内容】:
  %@",info);

//     
  [inputStream close];  
//关闭输入流

     
  [[NSRunLoop
mainRunLoop]run];
  //异步时用的  运行池 默认是关闭的
 打开就好

    }

   return
0;

}









 
  NSFileManager
*filemanager = [NSFileManager defaultManager];

 
  [filemanager createFileAtPath:@"/Users/ibokan/Desktop/mm/73.jpg" contents:self.reciveData attributes:nil]

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: