MyException - 我的异常网
当前位置:我的异常网» 移动开发 » ASIHttpRequest-创造和执行request 的 异步加载和使

ASIHttpRequest-创造和执行request 的 异步加载和使用块

www.myexceptions.net  网友分享于:2013-04-10  浏览:23次
ASIHttpRequest-创建和执行request 的 异步加载和使用块

ASIHttpRequest-创建和执行request

//---------  异步加载 -----------------

+ (void)grabURLInBackground
{
    NSURL *url = [NSURL URLWithString:@"http://localhost:3000/api/blog_lists"];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate:self];
//    [request setDidFailSelector:@selector(requestFailed:)];
//    [request setDidFinishSelector:@selector(requestFinished:)];
    [request startAsynchronous];
    
    [request setDefaultResponseEncoding:NSUTF8StringEncoding];
}

+ (void)requestFinished:(ASIHTTPRequest *)request
{
    // Use when fetching text data
    NSString *responseString = [request responseString];
    NSLog ( @"----------------%@" ,responseString);
    
    // Use when fetching binary data
//    NSData *responseData = [request responseData];
}

+ (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
}

+ (NSMutableArray *)getBlogList
{
    
//    [self grabURLInBackground];
    [self blockInBackground];
    return nil;
}

//---------  block块 -----------------
+ (void)blockInBackground
{
     NSURL *url = [NSURL URLWithString:@"http://localhost:3000/api/blog_lists"];
    
    __block ASIHTTPRequest *request = [ ASIHTTPRequest requestWithURL :url];
    
    // ASIHTTPRequest 支持 iOS 4.0 的块语法,你可以把委托方法定义到块中
    [request setCompletionBlock :^{
        // 请求响应结束,返回 responseString
        NSString *responseString = [request responseString ]; // 对于 2 进制数据,使用 NSData 返回 NSData *responseData = [request responseData];
        NSLog ( @"%@" ,responseString);
    }];
    
    [request setFailedBlock :^{
        // 请求响应失败,返回错误信息
        NSError *error = [request error ];
        NSLog ( @"error:%@" ,[error userInfo ]);
    }];
    
    [request startAsynchronous ];
}

文章评论

软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有