您的位置:首页 > 移动开发 > IOS开发

iOS开发之AFNetworking实现数据传输和文件上传

2015-05-13 23:09 411 查看
//传输数据

1 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];

//2.设置登录参数
NSDictionary *dict = @{ @"username":username, @"password":password, @"birthday":birthday, @"gender":gender, @"mobile":mobile, @"avstar":avster };
//3.请求
[manager POST:@"http://127.0.0.1/HelloServer/index.php/users/insert" parameters:dict success: ^(AFHTTPRequestOperation *operation, id responseObject) {

NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"POST --> %@, %@", result , [NSThread currentThread]); //自动返回主线程
UIWindow *window = [[UIApplication sharedApplication] keyWindow];
window.rootViewController = [AppDelegate tabBarController];

} failure: ^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@", error);
}];


//文件上传

1 NSData *data = UIImagePNGRepresentation(image);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
NSLog(@"filename:%@", fileName);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];

NSDictionary *parameters = @{@"foo": @"bar"};
[manager POST:@"http://localhost/HelloServer/index.php/index/upload/" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: