IOS   Objective c 同步 异步链接 …

本文介绍如何使用 Objective-C 进行网络请求(包括同步与异步),解析 XML 数据,并进行文件的创建、读取及移动等基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;

}

IOS <wbr> <wbr> <wbr>Objective <wbr>c <wbr>同步 <wbr>异步链接 <wbr> <wbr>网上下载图片到本地 <wbr> <wbr> <wbr>XML <wbr>,SBjson

IOS <wbr> <wbr> <wbr>Objective <wbr>c <wbr>同步 <wbr>异步链接 <wbr> <wbr>网上下载图片到本地 <wbr> <wbr> <wbr>XML <wbr>,SBjson

    NSFileManager *filemanager = [NSFileManager defaultManager];

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

IOS <wbr> <wbr> <wbr>Objective <wbr>c <wbr>同步 <wbr>异步链接 <wbr> <wbr>网上下载图片到本地 <wbr> <wbr> <wbr>XML <wbr>,SBjson


内容概要:该研究通过在黑龙江省某示范村进行24小时实地测试,比较了燃煤炉具与自动/手动进料生物质炉具的污染物排放特征。结果显示,生物质炉具相比燃煤炉具显著降低了PM2.5、CO和SO2的排放(自动进料分别降低41.2%、54.3%、40.0%;手动进料降低35.3%、22.1%、20.0%),但NOx排放未降低甚至有所增加。研究还发现,经济性和便利性是影响生物质炉具推广的重要因素。该研究不仅提供了实际排放数据支持,还通过Python代码详细复现了排放特征比较、减排效果计算和结果可视化,进一步探讨了燃料性质、动态排放特征、碳平衡计算以及政策建议。 适合人群:从事环境科学研究的学者、政府环保部门工作人员、能源政策制定者、关注农村能源转型的社会人士。 使用场景及目标:①评估生物质炉具在农村地区的推广潜力;②为政策制定者提供科学依据,优化补贴政策;③帮助研究人员深入了解生物质炉具的排放特征和技术改进方向;④为企业研发更高效的生物质炉具提供参考。 其他说明:该研究通过大量数据分析和模拟,揭示了生物质炉具在实际应用中的优点和挑战,特别是NOx排放增加的问题。研究还提出了多项具体的技术改进方向和政策建议,如优化进料方式、提高热效率、建设本地颗粒厂等,为生物质炉具的广泛推广提供了可行路径。此外,研究还开发了一个智能政策建议生成系统,可以根据不同地区的特征定制化生成政策建议,为农村能源转型提供了有力支持。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值