1. Create a single view project, import the ASIHttpRequest library, and import the four system libraries MobileCoreServices, CFNetwork, SystemConfiguration, and libz1.2.5.dylib.
2. Add an image as needed, such as haoyou.png
3. ViewController. h
#import
#import "ASIHTTPRequest.h"#import "ASIFormDataRequest.h"@interface ViewController : UIViewController @property (nonatomic, copy)NSString *m_auth;@end
4. Add two buttons for ViewController. m
-(Void) viewDidLoad {[super viewDidLoad]; UIButton * loginBtn = [UIButton buttonWithType: UIButtonTypeRoundedRect]; loginBtn. frame = CGRectMake (100, 20,120, 40); [loginBtn setTitle: @ "login" forState: UIControlStateNormal]; [loginBtn addTarget: self action: @ selector (login) forControlEvents: UIControlEventTouchUpInside]; [self. view addSubview: loginBtn]; UIButton * uploadBtn = [UIButton buttonWithType: UIButtonTypeRoundedRect]; uploadBtn. frame = CGRectMake (100, 80,120, 40); [uploadBtn setTitle: @ "upload" forState: UIControlStateNormal]; [uploadBtn addTarget: self action: @ selector (upload) forControlEvents: UIControlEventTouchUpInside]; [self. view addSubview: uploadBtn];}
5. Implement the login and upload Methods
-(Void) login {NSURL * url = [NSURL URLWithString :@"... "]; // The request url is omitted here // request ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL: url]; request. tag = 10; request. delegate = self; [request startAsynchronous];}-(void) upload {NSURL * url = [NSURL URLWithString :@"... "]; // The request url UIImage * img = [UIImage imageNamed: @" haoyou.png "]; NSData * data = UIImagePNGRepresentation (img); // ASIFormDataRequest is a post request, you can view the source code ASIFormDataRequest * request = [ASIFormDataRequest requestWithURL: url]; request. tag = 20; request. delegate = self; [request setPostValue: self. m_auth forKey: @ "m_auth"]; // [request setFile: @ "tabbar.png" forKey: @ "haoyou"]; // If a path exists, upload the file [request setData: data withFileName: @ "tmp.png" andContentType: @ "image/png" forKey: @ "headimage"]; // set the key [request startAsynchronous] for the data file name.}
6. Implementation Protocol
-(Void) requestFailed :( ASIHTTPRequest *) request {NSLog (@ "request failed");}-(void) requestFinished :( ASIHTTPRequest *) request {if (request. tag = 10) {NSDictionary * dic = [NSJSONSerialization JSONObjectWithData: request. responseData options: 0 error: nil]; self. m_auth = [dic objectForKey: @ "m_auth"]; NSLog (@ "% @", self. m_auth);} if (request. tag = 20) {NSLog (@ "% @", request. responseString );}}