ios oc 文件选择
时间: 2024-10-25 15:04:04 浏览: 11
iOS OC 加载动图(gif)
在iOS Objective-C中,文件选择通常涉及到用户从设备的文件系统中选择文件,这通常发生在需要访问用户相册、文档或其他本地文件的应用场景中。你可以使用`UIImagePickerController`来进行这样的操作。
首先,导入所需框架:
```objc
#import <UIKit/UIKit.h>
```
然后,在需要的视图控制器(UIViewController)中,实现`UIImagePickerControllerDelegate`协议,并设置代理:
```objc
@interface YourViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
```
接着,创建选择图片或文件的方法,比如选择照片:
```objc
- (IBAction)selectImage:(id)sender {
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.delegate = self;
imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; // 或者UIImagePickerControllerSourceTypeSavedPhotosAlbum
[self presentViewController:imagePickerController animated:YES completion:nil];
}
```
当用户选择完成后,会触发`imagePickerController:didFinishPickingMediaWithInfo:`方法,你可以在其中获取所选文件路径或数据:
```objc
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
UIImage *selectedImage = info[UIImagePickerControllerOriginalImage]; // 获取图片
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); // 获取沙盒路径
NSString *documentsDirectory = paths[0];
// 将图片保存到指定目录
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"selected_image.jpg"];
NSData *imageData = UIImagePNGRepresentation(selectedImage);
[imageData writeToFile:filePath atomically:YES];
[picker dismissViewControllerAnimated:YES completion:nil];
}
```
阅读全文