Send Textfield value into PHP MySQL using xcode 8

2019-09-12 10:16发布

问题:

I just want to ask on how to send textfield value into mysql database in xcode using obj c without any click action or with click action?

If the code below can retrieve and display JSON data from web server into xcode:

#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController

@synthesize username,email;

- (void)viewDidLoad {
    [super viewDidLoad];

    NSError *error;
    NSString *url_string    = [NSString stringWithFormat: @"http://localhost/test.php"];
    NSData *data            = [NSData dataWithContentsOfURL: [NSURL URLWithString:url_string]];
    NSMutableArray *json    = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    NSDictionary *dict      = [json firstObject];
    NSString *data1         = [dict valueForKey:@"username"];
    NSString *data2         = [dict valueForKey:@"email"];
    email.text              = data1;
    pw.text                 = data2;   
}
@end

How to post username, email value into mysql database? Is it the same technique applied on post method? Because I do not want to use SBJson classes (if possible).

回答1:

There are several ways to do it. First, it is important to notice that dataWithContentsOfURL is not an asynchronous request. Meaning that if you use it to transfer large data, there is a good chance that you will freeze the app. For async requests, you should use the NSURLRequest.

Having said that, there are excellent API to upload/download data asynchronously. One which is very frequently used, and well documented is AFNetworking. This is coded on top of NSURLRequest.

For example, in your PHP you can retrieve the fields from a POST statement like this:

<?php
  $username = $_POST["username"];
  $email = $_POST["email"];
?>

In your app, you can call the PHP script with a POST request in AFNetworking as follow:

NSString *username = @"username";
NSString *email = @"email";
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"yourUrl" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    NSLog(@"Sending POST request to server");

    [formData appendPartWithFormData:[username dataUsingEncoding:NSUTF8StringEncoding] name:@"username"];
    [formData appendPartWithFormData:[email dataUsingEncoding:NSUTF8StringEncoding] name:@"email"];

} error:nil];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];

NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {

    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"SERVER UPLOAD FRACTION COMPLETED: %f", uploadProgress.fractionCompleted);
    });

} completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

    NSLog(@"responseObject %@", responseObject);
    NSString *responseString = [[[NSString alloc] initWithData:responseObject encoding:NSASCIIStringEncoding] mutableCopy];
    NSLog(@"The respose is: %@", responseString);

    if(error) {
        NSLog(@"Error: %@", error);

    } else {
        NSLog(@"The response is: %@", responseString);
        // Do something with the response
    }
}];
[uploadTask resume];


回答2:

Try this code:

NSDictionary *jsondata = @{
                           @"username":email.text,
                           @"password":pw.text  

                          };


                NSString *requestString = [jsondata jsonStringWithPrettyPrint:YES];

                NSData *postData = [requestString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
                NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

                NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
                [request setURL:YOUR_URL_HERE];
                [request setHTTPMethod:@"POST"];
                [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
                [request setValue:@"application/json; charset=UTF-8 " forHTTPHeaderField:@"Content-Type"];
                [request setHTTPBody:postData];
            NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
            NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
            NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                //Handle your response here
            }];
            [task resume];