How to upload image to mysql database iOS applicat

2019-08-23 05:31发布

问题:

I'm new to iOS development and currently creating a app for my major project in uni. I'm creating a registration page where the user is asked to fill in their details and also upload an image. So far I've got the values going to the database but I can't figure out how to also add the image that has been selected by the image picker. Could anyone help with this? The code is posted below....

RegistrationViewController.h

#import <UIKit/UIKit.h>

#define kpostURL @"http://myurl.com/myphp.php"
#define kfname @"fname"
#define ksname @"sname"
#define kemail @"email"
#define kusername @"username"
#define kpassword @"password"
#define kinstrument @"instrument"
#define klocation @"location"

@interface registrationViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate> {

    UIScrollView *scrollView_;
    BOOL keyboardVisible_;

    IBOutlet UITextField *fnameText;
    IBOutlet UITextField *snameText;
    IBOutlet UITextField *emailText;
    IBOutlet UITextField *usernameText;
    IBOutlet UITextField *passwordText;
    IBOutlet UITextField *instrumentText;
    IBOutlet UITextField *locationText;
    IBOutlet UIImageView *ImageView;
    IBOutlet UIButton *button;

    NSURLConnection *postConnection;
}


@property (nonatomic, retain) UIImagePickerController *imagePicker;
@property (nonatomic, strong) IBOutlet UIScrollView *scrollView;

- (IBAction) pickImage:(id)sender;
- (IBAction) textFieldDoneEditing: (id) sender;
-(IBAction)post:(id)sender;


-(void) postMessage:(NSString*) location withName:(NSString *) fname withSurname:(NSString *) sname withEmail:(NSString *) email withUsername:(NSString *) username withPassword:(NSString *) password withInstrument:(NSString *) instrument;

- (void) keyboardDidShow:(NSNotification *)notif;
- (void) keyboardDidHide:(NSNotification *)notif;

@end

RegistrationViewController.m

#import "registrationViewController.h"
#import <QuartzCore/QuartzCore.h>

@implementation registrationViewController

@synthesize imagePicker;
@synthesize scrollView=scrollView_;

- (IBAction)textFieldDoneEditing:(id)sender {
    [sender resignFirstResponder];
}


- (IBAction)pickImage:(id)sender {
    imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentModalViewController:imagePicker animated:YES];
}

- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
        ImageView.image = image;
    [imagePicker dismissModalViewControllerAnimated:YES];
}


- (void) imagePickerControllerDidCancel:(UIImagePickerController *)picker {

    [imagePicker dismissModalViewControllerAnimated:YES];
}


#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

}


-(void) postMessage:(NSString*) location withName:(NSString *) fname withSurname:(NSString *) sname withEmail:(NSString *) email withUsername:(NSString *) username withPassword:(NSString *) password withInstrument:(NSString *) instrument{


    if (fname != nil && location != nil && sname !=nil && email !=nil && username !=nil && password !=nil && instrument !=nil){

        NSMutableString *postString = [NSMutableString stringWithString:kpostURL];

        [postString appendString:[NSString stringWithFormat:@"?%@=%@", kfname, fname]];

        [postString appendString:[NSString stringWithFormat:@"&%@=%@", ksname, sname]];

        [postString appendString:[NSString stringWithFormat:@"&%@=%@", kemail, email]];

        [postString appendString:[NSString stringWithFormat:@"&%@=%@", kusername, username]];

        [postString appendString:[NSString stringWithFormat:@"&%@=%@", kpassword, password]];

        [postString appendString:[NSString stringWithFormat:@"&%@=%@", kinstrument, instrument]];

        [postString appendString:[NSString stringWithFormat:@"&%@=%@", klocation, location]];

        [postString setString:[postString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:postString]];
        [request setHTTPMethod:@"POST"];

        postConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];


    }

}

-(IBAction)post:(id)sender{

    [self postMessage:locationText.text withName:fnameText.text withSurname:snameText.text withEmail:emailText.text withUsername:usernameText.text withPassword:passwordText.text withInstrument:instrumentText.text];
    [locationText resignFirstResponder];
    fnameText.text = nil;
    snameText.text = nil;
    emailText.text = nil;
    usernameText.text = nil;
    passwordText.text = nil;
    instrumentText.text = nil;
    locationText.text = nil;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Test1" object:self];

}

- (void)viewDidUnload
{
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{

    NSLog(@"%@", @"Registering for keyboard events...");
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
    keyboardVisible_ = NO;

    [super viewWillAppear:animated];

}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{

    NSLog(@"%@", @"Unregistering for keyboard events...");
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

#pragma mark -
#pragma mark Keyboard handlers

- (void) keyboardDidShow:(NSNotification *)notif {
    NSLog(@"%@", @"Received UIKeyboardDidShowNotification");

    if (keyboardVisible_) {
        NSLog(@"%@", @"Keyboard is already visible.  Ignoring notifications.");
        return;
    }

    // The keyboard wasn't visible before
    NSLog(@"Resizing smaller for keyboard");

    // Get the origin of the keyboard when it finishes animating
    NSDictionary *info = [notif userInfo];
    NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];

    // Get the top of the keyboard in view's coordinate system. 
    // We need to set the bottom of the scrollview to line up with it
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    CGFloat keyboardTop = keyboardRect.origin.y;

    // Resize the scroll view to make room for the keyboard
    CGRect viewFrame = self.view.bounds;
    viewFrame.size.height = keyboardTop - self.view.bounds.origin.y;

    self.scrollView.frame = viewFrame;
    keyboardVisible_ = YES;
}

- (void) keyboardDidHide:(NSNotification *)notif {
    NSLog(@"%@", @"Received UIKeyboardDidHideNotification");

    if (!keyboardVisible_) {
        NSLog(@"%@", @"Keyboard already hidden.  Ignoring notification.");
        return;
    }

    // The keyboard was visible
    NSLog(@"%@", @"Resizing bigger with no keyboard");

    // Resize the scroll view back to the full size of our view
    self.scrollView.frame = self.view.bounds;
    keyboardVisible_ = NO;
}

@end

Thanks in advance :)

回答1:

Here is a category that I've created on NSMutableURLRequest:

@interface NSMutableURLRequest (SendFormData)

-(void)sendFormData:(NSDictionary *)data;

@end

@implementation NSMutableURLRequest (SendFormData)

-(void)sendFormData:(NSDictionary *)data{
    // add boundary
    NSMutableString *boundary = [NSMutableString stringWithString:@"----Boundary+"];

    // append 5 random chars to the end of the boundary
    for(int i = 0; i < 5; i++){
        BOOL lowercase = arc4random() % 2;
        if(lowercase){
            [boundary appendFormat:@"%c", (arc4random() % 26) + 97];
        } else{
            [boundary appendFormat:@"%c", (arc4random() % 26) + 65];
        }
    }

    // create body data
    NSMutableData *body = [[NSMutableData alloc] init];

    self.HTTPMethod = @"POST";
    [self setValue:[NSString stringWithFormat:@"multipart/form-data, boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];

    for(NSString *currentKey in [data allKeys]){
        id currentObject = [data objectForKey:currentKey];
        if([currentObject class] == [UIImage class]){
            [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary]  dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"myphoto.png\"\r\n", currentKey] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[@"Content-Type: image/x-png\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
            [body appendData:[@"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:UIImagePNGRepresentation(currentObject)];
            [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        } else{
            [body appendData:[[NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n%@\r\n", boundary, currentKey, currentObject] dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]];
        }
    }

    self.HTTPBody = body;
}

@end

Just pass it a NSDictionary of your parameters and the parameters' objects, and it will create your request that you can then pass to a NSURLConnection.

Or you optionally can look into ASIFormDataRequest for such things (https://github.com/pokeb/asi-http-request/tree).