iOS开发中对于NSURLRequest的封装

在ios开发中经常用到NSURLRequest类来进行url请求,通常有以下步骤

1.实例化NSURL;

2.实例化NSURLRequest;

3.连接[NSURLConnection connectionWithRequest:request delegate:self];

4.实现NSURLConnectionDataDelegate协议;

这样的话比较繁琐,可以对其进行封装

1.新建一个MyUrlRequest类

MyUrlRequest.h文件

@interface MyUrlRequest : NSObject <NSURLConnectionDataDelegate> {
    NSMutableData *_mData;//接收数据
}  

@property (nonatomic, copy) NSString *urlStr;
@property (nonatomic, copy) void (^finishBlock)(NSData *data);//请求成功回调block
@property (nonatomic, copy) void (^failedBlick)();//请求失败回调block
@property (nonatomic, assign) BOOL isCache;//是否缓存

- (void)startRequest;//开始请求

@end

MyUrlRequest.m文件

#import "MyUrlRequest.h"
#import "NSString+Hashing.h"

@implementation QFURLRequest

@synthesize urlStr;
@synthesize finishBlock;
@synthesize failedBlick;
@synthesize isCache;

- (id)init {
    if (self = [super init]) {
        _mData = [[NSMutableData alloc] init];
    }
    return self;
}

- (void)startRequest {
    //MyRequestManager里边autorelease掉,在这里可能出错,所以需要retain
    [self retain];
    if (self.isCache) {
        //如果有缓存,则使用缓存
        NSString *path = [NSHomeDirectory() stringByAppendingFormat:@"/tmp/%@", [self.urlStr MD5Hash]];
        NSFileManager *manager = [NSFileManager defaultManager];
        if ([manager fileExistsAtPath:path]) {
            NSData *data = [NSData dataWithContentsOfFile:path];
            self.finishBlock(data);
            return;
        }
    }
    
    NSURL *url = [NSURL URLWithString:self.urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection connectionWithRequest:request delegate:self];
}
//实现NSURLConnectionDataDelegate协议
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [_mData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [self release];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    //写缓存
    if (self.isCache) {
        NSString *path = [NSHomeDirectory() stringByAppendingFormat:@"/tmp/%@", [self.urlStr MD5Hash]];
        [_mData writeToFile:path atomically:YES];
    }
    
    self.finishBlock(_mData);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [self release];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    self.failedBlick();
}

- (void)dealloc {
    [_mData release];
    self.finishBlock = nil;
    self.failedBlick = nil;
    [super dealloc];
}

@end

2.新建一个MyRequestManager类

.h文件

#import <Foundation/Foundation.h>
#import "MyUrlRequest.h"

@interface MyRequestManager : NSObject

+ (void)requestWithUrl:(NSString *)urlString andIsCache:(BOOL)isCache finish:(void(^)(NSData *data))finishBlock failed:(void(^)())failedBlock;

@end

.m文件

#import "MyRequestManager.h"

@implementation MyRequestManager

+ (void)requestWithUrl:(NSString *)urlString andIsCache:(BOOL)isCache finish:(void(^)(NSData *data))finishBlock failed:(void(^)())failedBlock
{
    MyUrlRequest *request = [[[MyUrlRequest alloc] init] autorelease];
    request.urlStr = urlString;
    request.isCache = isCache;
    request.finishBlock = finishBlock;
    request.failedBlick =  failedBlock;
    //在发送startRequest消息之后,该类方法结束,可能会对request发送autorelease消息,这样的话在request的startRequest方法中就可能会产生错误,所以要在startRequest方法中retain一下
    [request startRequest];
}

@end

这样的话,以后再发送请求就可以直接调用
[MyRequestManager requestWithUrl:(NSString *)urlString andIsCache:(BOOL)isCache finish:(void(^)(NSData *data))finishBlock failed:(void(^)())failedBlock];

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将Java的BufferedImage对象放入Map返回给iOS端,可以使用以下步骤: 1. 创建一个Map对象,并将BufferedImage对象放入其。 2. 将Map对象转换为JSON格式的字符串。 3. 使用HTTP协议将JSON字符串发送到iOS端。 4. 在iOS端接收HTTP响应的JSON字符串,将其解析为NSDictionary对象,并从获取BufferedImage对象。 以下是一个简单的示例代码: Java端: ``` // 读取图片并转换为BufferedImage对象 BufferedImage image = ImageIO.read(new File("path/to/image.jpg")); // 创建一个Map对象,并将BufferedImage对象放入其 Map<String, Object> map = new HashMap<>(); map.put("image", image); // 将Map对象转换为JSON格式的字符串 ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writeValueAsString(map); // 将JSON字符串返回给客户端 return jsonString; ``` iOS端: ``` NSURL *url = [NSURL URLWithString:@"http://your-java-server.com/get-image"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { if (data) { // 解析JSON字符串为NSDictionary对象 NSError *error = nil; NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; // 从NSDictionary对象获取BufferedImage对象 NSData *imageData = [[NSData alloc] initWithBase64EncodedString:jsonDict[@"image"] options:NSDataBase64DecodingIgnoreUnknownCharacters]; UIImage *image = [UIImage imageWithData:imageData]; // 在这里使用UIImage对象 } else { NSLog(@"%@", error); } }]; ``` 注意:在实际开发,要考虑到JSON序列化和反序列化的效率,以及图片大小、网络传输速度等因素,以保证图片的快速加载和显示。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值