如何在 iphone 应用程序中上传照片?

How to upload photos in iphone app?

我正在创建一个练习地址簿应用程序,我想添加用户上传他的照片的功能。我在网上搜索过,但找不到有关如何实现这一点的有用教程。

如果有人知道有关上传图片的好教程,请分享。

还有一件事,如果用户上传his/her图片,我希望图片也存储在核心数据中,这样它就可以显示在Table视图控制器和一个更新视图控制器,用户可以在其中上传新图像并替换之前的图像。

任何对此进行解释的好教程都会有所帮助。

提前致谢

首先请在询问任何question.You需要使用 UImagePickerController 之前做一些研究,像这样:

您需要将这些代表添加到您的 viewController

UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate.

一旦您希望用户选择图片

[[[UIActionSheet alloc] initWithTitle:@"Choose media type"
                             delegate:self
                    cancelButtonTitle:@"Cancel"
               destructiveButtonTitle:nil
                    otherButtonTitles:@"Camera", @"Library", nil] showInView:self.view];

这将显示一个 UIActionSheet,以便用户可以从相机或库中进行选择

用户选择其中一个选项后,将调用 UIActionSheet 委托方法

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    switch (buttonIndex) {
        case 0:
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            break;
        case 1:
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            break;
    }

    [self presentViewController:picker animated:YES completion:NULL];
}

在这里你可以让用户选择以太添加相机或添加库

现在,在用户选择照片(图库/相机)后,将调用 UIImagePickerControllerDelegate 方法

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
}

chosenImage 是用户从 UIImagePickerController 选择的图像。

我建议你使用 AFNetworking

    NSString *BASE_URL = ... //Your server base url
    AFHTTPRequestOperationManager *operationManager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:BASE_URL]];
    NSString *path = ... //Your relative path
    NSDictionary *params = @{};//Your params
    [operationManager POST:@"" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if (mediaFile) {
            [formData appendPartWithFileData:mediaFile name:@"name" fileName:@"fileName" mimeType:@"image/jpeg"];
        }
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    }];