在上篇文章中,阿堂和网友们分享了如何用ASIHTTPRequest框架下载数据的实例,本篇阿堂将数据介绍如何用ASIHTTPRequest框架上传数据的应用实例。
#import
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "NSNumber+Message.h"
#import "NSString+URLEncoding.h"
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIImageView *imageView1;
@property (weak, nonatomic) IBOutlet UIImageView *imageView2;
- (IBAction)onClick:(id)sender;
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)onClick:(id)sender {
NSString *strURL1 = @"http://www.crazyit.com/service/upload.php";
NSURL *url1 = [NSURL URLWithString:[strURL1 URLEncodedString]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url1];
[request setPostValue:@"heyitang@qq.com" forKey:@"email"];
NSString *path = [[NSBundle mainBundle] pathForResource:@"test1" ofType:@"jpg"];
[request setFile:path forKey:@"file"];
[request setDelegate:self];
[request setDidFinishSelector:@selector(requestSuccess:)];
[request setDidFailSelector:@selector(requestError:)];
[request startAsynchronous];
}
- (void)requestSuccess:(ASIHTTPRequest *)request
{
NSData *data = [request responseData];
NSError *eror;
NSDictionary *resDict = [NSJSONSerialization JSONObjectWithData:dataoptions:NSJSONReadingAllowFragments error:&eror];
if (!resDict) {
//查看图片
[self seeImage];
} else {
NSNumber *resultCodeObj = [resDict objectForKey:@"ResultCode"];
NSString *errorStr = [resultCodeObj errorMessage];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"错误信息"
message:errorStr
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alertView show];
}
}
- (void)requestError:(ASIHTTPRequest *)request
{
NSError *error = [request error];
NSLog(@"%@",[error localizedDescription]);
}
-(void)seeImage
{
NSString *strURL = [[NSString alloc] initWithFormat:@"http://www.crazyit.com/service/download.php?email=%@&FileName=test1.jpg",@"heyitang@qq.com"];
NSURL *url = [NSURL URLWithString:[strURL URLEncodedString]];
__weak ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setCompletionBlock:^{
NSData *data = [request responseData];
UIImage *img = [UIImage imageWithData:data];
_imageView1.image = img;
}];
[request setFailedBlock:^{
NSError *error = [request error];
NSLog(@"%@", [error localizedDescription]);
}];
[request startAsynchronous];
}
@end