简体   繁体   中英

How to send data to PHP server?

i`m having a problem doing this code to send a data to my php server can someone help me. this is my code that gives me a headache, this is my Outlets/ textfield.

@property (weak, nonatomic) IBOutlet UITextField *parentsNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *professionTextField;
@property (weak, nonatomic) IBOutlet UITextField *addressTextField;
@property (weak, nonatomic) IBOutlet UITextField *contactTextField;
@property (weak, nonatomic) IBOutlet UITextField *emailAddressTextField;
@property (weak, nonatomic) IBOutlet UITextField *osTypeTextField;

and this is the Action Button

- (IBAction)registerButtonTapped:(id)sender {


 NSString *post = [NSString stringWithFormat:@"&parentNameTextField=%@&professionTextField=%@",@"parentNameTextField",@"professionTextField"];



NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];




[request setURL:[NSURL URLWithString:@"http://a7c8a2a.ngrok.com/usermanagement_dummy/user/register"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (conn)
{
    NSLog(@"Connection Success");

}
else
{
    NSLog(@"Connection could not be made");

}

}

i m trying my best to continue but i don t know how to. any help would be gladly appreciate.

NSMutableDictionary *get = [[NSMutableDictionary alloc]init];
[get setObject:@"parentNameTextField" forKey:@"parentNameTextField"]; 
[get setObject:@"parentNameTextField" forKey:@"professionTextField"]; 


if([NSJSONSerialization isValidJSONObject:get]){


//convert object to data
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:get options:kNilOptions error:nil];


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://a7c8a2a.ngrok.com/usermanagement_dummy/user/register"]];


[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:jsonData];


NSURLSessionConfiguration *config=[NSURLSessionConfiguration defaultSessionConfiguration];

NSURLSession *session=[NSURLSession sessionWithConfiguration:config];

NSURLSessionDataTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    if(response){
        NSString *resp = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
        NSLog(@"Echo %@",resp);


    }

    else{
        NSLog(@"Timeout");

    }



}];
[task resume];


}

Make a dictionary of key value pair.Then create q request and NSURLSessionDataTask to POST your parameters.In the completion handler code u can get response also u can add error handling in dataTaskWithRequest completion handler Try the below code.This will work for you

You can pass data through AFNetworking to php server

  NSMutableDictionary *dictData = [[NSMutableDictionary alloc]init];
  [dictData setValue:txtUserName.text forKey:@"user"];
  [dictData setValue:txtPassword.text forKey:@"pass"];

Use this method for pass request

NSDictionary *parameters = @{ @"name":@"login", @"body": dictData
        };
        NSString *bodyString = [self jsonStringFromID:parameters isPretty:NO];
        NSData *tempData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
        NSString *bodyRequest = [[NSString alloc] initWithData:tempData encoding:NSUTF8StringEncoding];
        bodyRequest = [NSString stringWithFormat:@"json=%@", bodyRequest];
        NSData *bodyData = [bodyRequest dataUsingEncoding:NSUTF8StringEncoding];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:CMS_HTML_URL]];
        [request setTimeoutInterval:TIME_OUT];
        [request setHTTPMethod:@"POST"];
        [request setHTTPBody:bodyData];
        AFHTTPRequestOperation *op = [[AFNetworkingClient sharedClient] HTTPRequestOperationWithRequest:request success: ^(AFHTTPRequestOperation *operation, id responseObject) {
            if ([CommonMethods isObjectEmpty:responseObject]) {
            //display alert when responseObject nil
            }
            else {
                if ([[responseObject valueForKey:@"success"] boolValue]) {
                   //print the response 
                }
            }
        } failure: ^(AFHTTPRequestOperation *operation, NSError *error) {
            //CR 6 July 2015

           //print the error
        }];
        op.responseSerializer = [kAFNetworkingClient responseSerializer];
        [[[AFNetworkingClient sharedClient] operationQueue] addOperation:op];
        [op start];

pass request parameter to string

- (NSString *)jsonStringFromID:(id)object isPretty:(BOOL)prettyPrint {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:(NSJSONWritingOptions)(prettyPrint ? NSJSONWritingPrettyPrinted : 0)
                                                         error:&error];

    if (!jsonData) {
        //NSLog(@"Json Print: error: %@", error.localizedDescription);
        return @"{}";
    }
    else {
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM