iOS上傳頭像(UIImagePickerController)

好久沒更新了,今天準(zhǔn)備寫一個在實(shí)戰(zhàn)項目中大家經(jīng)常遇到的,就是圖片上傳頭像。 下面介紹從本地上傳。首先,一般我們頭像是需要保存在本地的,所以我們要建個本地類,用來存圖片字節(jié)。
UserDefaults.m文件

#import "UserDefaults.h"

@implementation UserDefaults

+ (void)setImage:(NSData *)img
{
    [[NSUserDefaults standardUserDefaults] setObject:img forKey:@"img"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (NSData *)getImage
{
    return [[NSUserDefaults standardUserDefaults] objectForKey:@"img"];
}

@end

然后在你的控制器頁面將UserDefaults.h導(dǎo)進(jìn)來。

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width / 2)];
    [_topView setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:_topView];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, _topView.frame.size.width, _topView.frame.size.height)];
    [imageView setBackgroundColor:[UIColor clearColor]];
    [imageView setImage:[UIImage imageNamed:@"chen.png"]];
    [_topView addSubview:imageView];
    
    _avatarBtn = [[UIButton alloc] initWithFrame:CGRectMake((imageView.frame.size.width - 70) / 2, (imageView.frame.size.height - 70) / 2, 70, 70)];
    _avatarBtn.layer.masksToBounds = YES;
    _avatarBtn.layer.cornerRadius = _avatarBtn.frame.size.height / 2;
    _avatarBtn.layer.borderWidth = 1.0f;
    _avatarBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    [_avatarBtn setBackgroundImage:[UIImage imageNamed:@"loin_icon_noSelect"] forState:UIControlStateNormal];
    [_avatarBtn addTarget:self action:@selector(onImageTouch:) forControlEvents:UIControlEventTouchUpInside];
    [_topView addSubview:_avatarBtn];
}

初始化創(chuàng)建所需要的控件。接下來,在點(diǎn)擊按鈕的事件中,我們就來個提示框提示是否選擇圖片或拍照,都是在一個點(diǎn)擊事件的方法里面

- (void)onImageTouch:(UIButton *)btn
{
    UIAlertController *alertSheet = [UIAlertController alertControllerWithTitle:@"請選擇頭像來源" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    
    // 判斷是否支持相機(jī)
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])  {
        UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)  {
            // 設(shè)置數(shù)據(jù)源
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }];
        [alertSheet addAction:cameraAction];
    }
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"從手機(jī)相冊選擇" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }];
        [alertSheet addAction:photoAction];
    }
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertSheet addAction:cancelAction];
    [self presentViewController:alertSheet animated:YES completion:nil];
}

之后,我們就去寫UIImagePickerController的代理方法,當(dāng)取消或選中之后的操作:

#pragma mark -
#pragma mark UIImagePickerControllerDelegate

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    // 被選中的圖片
    if ([mediaType isEqualToString:@"public.image"])   {
        // 獲取照片
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        NSString *path = [self saveImg:image WithName:@"avatar.png"];
        if (path != nil)  {
            // 圖片存在,做你想要的操作
            NSData *data = [NSData dataWithContentsOfFile:path];
            [UserDefaults setImage:data];
        }
        [picker dismissViewControllerAnimated:YES completion:nil];          // 隱藏視圖
    }
}

我們需要寫一個圖片保存到本地的方法

// 圖片保存本地

- (NSString *)saveImg:(UIImage *)curImage WithName:(NSString *)imageName;
{
    NSData *imageData = UIImageJPEGRepresentation(curImage, 1);             // 1為不縮放保存,取值(0~1)
    
    // 獲取沙盒路徑
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:imageName];
    
    // 將照片寫入文件
    //atomically:這個參數(shù)意思是: 如果為YES則保證文件的寫入原子性,就是說會先創(chuàng)建一個臨時文件,直到文件內(nèi)容寫入成功再導(dǎo)入到目標(biāo)文件里.如果為NO,則直接寫入目標(biāo)文件里
    if ([imageData writeToFile:path atomically:NO]) {
        return path;
    }  else {
        return nil;
    }
}

到了這里已經(jīng)把圖片從手機(jī)相冊還是手機(jī)拍照之后傳到了頭像控件里面了。但是要注意,我們是本地保存,所以再每次進(jìn)入到視圖View的時候都要記得取加載保存過的那張圖片

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    if ([UserDefaults getImage].length > 0) {
        [_avatarBtn setImage:[UIImage imageWithData:[UserDefaults getImage]] forState:UIControlStateNormal];
    } else {
        // 否則,獲取你從服務(wù)器上加載的圖片(讀者的建議,很nice),獲取后記得把圖片保存本地,這樣長度就有啦
        [_avatarBtn setImage@“服務(wù)器上加載的圖片” forState:UIControlStateNormal];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
}

最后,提醒一點(diǎn),記得把訪問跟拍照權(quán)限添加進(jìn)來,這不列舉一下

截圖01.png

NSMicrophoneUsageDescription 是否允許此App使用您的麥克風(fēng)?
NSPhotoLibraryUsageDescription 是否允許此App使用您的相冊?
NSContactsUsageDescription 是否允許此App訪問您的通訊錄?
NSCameraUsageDescription 是否允許此App使用您的 相機(jī)?
NSCalendarsUsageDescription 是否允許此App使用日歷?
NSAppleMusicUsageDescription 媒體資料庫

效果圖:


截圖02.png

好了,大概圖片上傳也就這些啦,簡單易懂。全部代碼都貼出來了,背景框是我女神,大家猜一猜嘍。我會再繼續(xù)分享自己的菜鳥經(jīng)歷中的心得,感謝了!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,765評論 25 709
  • 設(shè)置代理 點(diǎn)擊頭像按鈕: 調(diào)用相機(jī)相冊,顯示中文將Info.plist 文件中的Localization nati...
    ZIM東東閱讀 2,107評論 1 5
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,506評論 19 139
  • 你和我都是孤獨(dú)的鬼 承受著滿身疲憊 也許有天我們流出眼淚 那樣子十分狼狽 我們是孤獨(dú)的鬼 可是我們無罪.
    大小姐222閱讀 173評論 0 0
  • 神農(nóng)嘗百草, 袁翁醉豐稻。 不關(guān)利與名, 惟求饑民飽。 (新韻) 注:以下內(nèi)容轉(zhuǎn)載自馮站長之家《這項突破,...
    任爾風(fēng)云我自逍閱讀 356評論 8 8

友情鏈接更多精彩內(nèi)容