iOS开发之AFNetworking实现数据传输和文件上传
//传输数据
1 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 2 manager.responseSerializer = [AFHTTPResponseSerializer serializer]; 3 manager.requestSerializer = [AFHTTPRequestSerializer serializer]; 4 5 //2.设置登录参数 6 NSDictionary *dict = @{ @"username":username, @"password":password, @"birthday":birthday, @"gender":gender, @"mobile":mobile, @"avstar":avster }; 7 //3.请求 8 [manager POST:@"http://127.0.0.1/HelloServer/index.php/users/insert" parameters:dict success: ^(AFHTTPRequestOperation *operation, id responseObject) { 9 10 NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; 11 NSLog(@"POST --> %@, %@", result , [NSThread currentThread]); //自动返回主线程 12 UIWindow *window = [[UIApplication sharedApplication] keyWindow]; 13 window.rootViewController = [AppDelegate tabBarController]; 14 15 } failure: ^(AFHTTPRequestOperation *operation, NSError *error) { 16 NSLog(@"%@", error); 17 }];
//文件上传
1 NSData *data = UIImagePNGRepresentation(image); 2 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 3 formatter.dateFormat = @"yyyyMMddHHmmss"; 4 NSString *str = [formatter stringFromDate:[NSDate date]]; 5 NSString *fileName = [NSString stringWithFormat:@"%@.png", str]; 6 NSLog(@"filename:%@", fileName); 7 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 8 manager.responseSerializer = [AFHTTPResponseSerializer serializer]; 9 manager.requestSerializer = [AFHTTPRequestSerializer serializer]; 10 11 NSDictionary *parameters = @{@"foo": @"bar"}; 12 [manager POST:@"http://localhost/HelloServer/index.php/index/upload/" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 13 [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"]; 14 } success:^(AFHTTPRequestOperation *operation, id responseObject) { 15 NSLog(@"Success: %@", responseObject); 16 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 17 NSLog(@"Error: %@", error); 18 }];
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。