https://github.com/AFNetworking/AFNetworking這裏有着很好的例子, 我如何使用這個東西 1.創建客戶端實例,這將每一次服務的應用程序將需要連接到服務器
file.h
#import "AFHTTPRequestOperationManager.h"
@interface YourClient : AFHTTPRequestOperationManager
+ (instancetype)sharedClient;
- (void)send_Image_POST_WS:(NSString *)ws_name image:(NSData*)imageData param:(NSDictionary *)param :(void (^)(NSDictionary *json, NSError *error, NSInteger status))block;
file.m
static NSString * const YouBaseURLString = @"http://blablabla";
@implementation YourClient
+ (instancetype)sharedClient {
static YourClient *_sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedClient = [[YourClient alloc] initWithBaseURL:[NSURL YouBaseURLString]];
_sharedClient.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
});
return _sharedClient;
}
// you can change the block according to the needs of its receiver
- (void)send_Image_POST_WS:(NSString *)ws_name image:(NSData*)imageData param:(NSDictionary*)param :(void (^)(NSDictionary *json, NSError *error, NSInteger status))block{
// NSLog(@「WS: %@\nPARAMS: --> %@",ws_name,[param description]);
[self POST:ws_name parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:@"imagedata" fileName:@"imagedata.png" mimeType:@"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (block) {
// NSLog(@"WS:%@\nRESPONSE : -> %@",ws_name,responseObject);
block(responseObject,nil,operation.response.statusCode);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//NSLog(@"Response error text %@",operation.responseString);
// you can display here alert
if (block) {
block(nil,error,operation.response.statusCode);
}
}];
}
- 類,其具有要發送的圖像例如
ProfileViewController.m
-(void)send_UploadImage:(UIImage *)image{
// here you can activate a spinner (use which one you want - of Apple or some open source)
NSDictionary *params = @{@"extension":@"png",
@「usr_id」:@「1」};// <<<—— this is an additional data the service on the server side will need, just example, replace with needed
NSData *dataImage = UIImageJPEGRepresentation(image, 0.5);
// @"common/upload_image" replace with your path to the service on the server side, it will be added to the Base URL
[[YourClient sharedClient] send_Image_POST_WS:@"common/upload_image" image:dataImage param:params :^(NSDictionary *json, NSError *error) {
// hide spinner
if (!error) {
// read json, change UI here you are on the main thread
}else{
// react accordingly main thread
}
}];
}
謝謝!該代碼顯示瞭如何在沒有文件的情況下發布多個值。怎麼做? – Donny 2015-04-06 07:55:06