相機選擇照片及拍照後使用AFNetworking圖片上傳(支持一張及多張上傳)


彈出照片獲取方式
- (IBAction)changeTheImage:(UIButton *)sender {
    selectedButton = sender;
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相冊",@"相機", nil];
    [sheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex != actionSheet.cancelButtonIndex) {
        if (buttonIndex == 0) {
            //相冊
            [self goAlbum];
        } else if (buttonIndex == 1) {
            //相機
            [self takePhoto];
        }
    }
}

//開始拍照
-(void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: sourceType]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.sourceType = sourceType;
        picker.modalTransitionStyle=UIModalTransitionStyleCoverVertical;
        picker.videoQuality = UIImagePickerControllerQualityTypeMedium;
        [self presentViewController:picker animated:YES completion:^{
            
        }];
    }
}

//相冊選擇
- (void)goAlbum {
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.modalTransitionStyle=UIModalTransitionStyleCoverVertical;
        picker.videoQuality = UIImagePickerControllerQualityTypeMedium;
        [self presentViewController:picker animated:YES completion:^{
            
        }];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    //當選擇的類型是圖片
    //先把圖片轉成NSData
    UIImage* image = [info objectForKey:UIImagePickerControllerOriginalImage];
    //關閉相冊界面
    __weak __typeof(self)weakSelf = self;
    [picker dismissViewControllerAnimated:YES completion:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            [dict setObject:image forKey:@"image"];
            if (selectedButton == weakSelf.cardFrontButton) {
                [dict setObject:@"card_img" forKey:@"type"];
                if (images.count < 1) {
                    [images addObject:dict];
                } else {
                    [images replaceObjectAtIndex:0 withObject:dict];
                }
                [weakSelf.cardFrontButton setBackgroundImage:image forState:UIControlStateNormal];
                [weakSelf.cardFrontButton.currentBackgroundImage setAccessibilityIdentifier:@"imagePicked"];
            } else if (selectedButton == weakSelf.co_Button) {
                
                [dict setObject:@"witness_one_img" forKey:@"type"];
                if (images.count < 2) {
                    [images addObject:dict];
                } else {
                    [images replaceObjectAtIndex:1 withObject:dict];
                }
                [weakSelf.co_Button setBackgroundImage:image forState:UIControlStateNormal];
                [weakSelf.co_Button.currentBackgroundImage setAccessibilityIdentifier:@"imagePicked"];
            }
        });
    }];
}

//上傳照片 單張上傳,將for循環去掉,獲取到自己的需要上傳的照片即可        多張上傳的時候,利用for 循環,將照片一次性以form表單的形式提交到後臺
- (void)imageUpload {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"loginName": self.scaningDict[@"username"],@"phone_num" : self.scaningDict[@"phoneNum"], @"session_id" :  self.scaningDict[@"sessionId"]};
    [manager POST:[NSString stringWithFormat:@"%@%@",SERVER_ADDRESS,URL_PHOTO_MENHU] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        for (int i = 0; i < images.count; i ++) {
            NSMutableDictionary *dict = images[i];
            NSData *data=UIImageJPEGRepresentation(dict[@"image"], .5);
            [formData appendPartWithFileData:data name:dict[@"type"] fileName:@"" mimeType:@""];
        }
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        id code=[responseObject objectForKey:@"code"];
        if ([code intValue] == 200) {
            dispatch_async(dispatch_get_main_queue(), ^{
                HideIndicator_InView(self.view);
                ShowTips(@"上傳成功,請到門戶查看");
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popToRootViewControllerAnimated:YES];
                });
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                HideIndicator_InView(self.view);
                ShowTips(@"上傳失敗,請重新上傳");
                return ;
            });
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            HideIndicator_InView(self.view);
            ShowTips(@"上傳失敗,請重新上傳");
            return ;
        });
    }];
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章