iOS 圖片上傳的兩種方式
來源:互聯網
上載者:User
我們在寫代碼的時候經常會將頭像進行上傳伺服器,上傳頭像圖片我試過兩種方式
一種方式就是使用base64字串上傳圖片,這種形式我個人認為比較適合上傳圖片數量比較少的,比如上傳頭像,上傳圖片數量多的話,速度會慢些
另一種方式是使用二進位流進行上傳圖片,這種方式上傳圖片少或者數量多都沒關係,速度也很快
demo地址: https://github.com/tuwanli/PictureHead
選擇頭像效果:
程式如下:
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController :
UIViewController
@property (weak,
nonatomic) IBOutlet
UIImageView *headIcon;
- (IBAction)changeIconAction:(UITapGestureRecognizer *)sender;
@end
ViewController.m
#import "ViewController.h"
#import "AFHTTPRequestOperationManager.h"
@interface
ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>
{
UIImagePickerController *pickerController;
AFHTTPRequestOperationManager *manager;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super
viewDidLoad];
//初始化頭像控制項
[self
initHeadIcon];
//初始化pickController
[self
createData];
}
- (void)initHeadIcon
{
self.view.backgroundColor = [UIColor
lightGrayColor];
self.headIcon.layer.cornerRadius
= self.headIcon.frame.size.height/2;
self.headIcon.clipsToBounds =
YES;
self.headIcon.layer.borderColor
= [UIColor whiteColor].CGColor;
self.headIcon.layer.borderWidth
= 3;
}
- (void)createData
{
//初始化pickerController
pickerController = [[UIImagePickerController
alloc]init];
pickerController.view.backgroundColor = [UIColor
orangeColor];
pickerController.delegate =
self;
pickerController.allowsEditing =
YES;
}
- (IBAction)changeIconAction:(UITapGestureRecognizer *)sender {
UIActionSheet *actionSheet = [[UIActionSheet
alloc]initWithTitle:@"選擇頭像"
delegate:self
cancelButtonTitle:@"取消"
destructiveButtonTitle:nil
otherButtonTitles:@"拍照",@"相簿",@"圖庫",
nil];
[actionSheet showInView:[UIApplication
sharedApplication].keyWindow];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex ==
0) {//相機
if([UIImagePickerController
isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
NSLog(@"支援相機");
[self
makePhoto];
}else{
UIAlertView *alert = [[UIAlertView
alloc]initWithTitle:@"提示"
message:@"請在設定-->隱私-->相機,中開啟本應用的相機存取權限。。"
delegate:self
cancelButtonTitle:@"取消"
otherButtonTitles:@"我知道了",