2013-03-23 10 views
9

Próbuję następujący kod, który wykonuje po wprowadzeniu danych przez użytkownika w polach (tytuł, opis, miasto), a następnie kliknięć Zapisz.przesyłaj dane do skryptu PHP z iOS

- (IBAction)saveDataAction:(id)sender { 
    NSString *lEventTitle = [NSString stringWithFormat:@"var=%@",eventTitle.text]; 
    NSString *lEventDesc = [NSString stringWithFormat:@"var=%@",eventDescription.text]; 
    NSString *lEventCity = [NSString stringWithFormat:@"var=%@",eventCity.text]; 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mydomain.com/ios/form.php"]]; 
    [request setHTTPMethod:@"POST"]; 
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"]; 
    //this is hard coded based on your suggested values, obviously you'd probably need to make this more dynamic based on your application's specific data to send 

    NSString *postString = [[NSString alloc] initWithFormat:@"title=%@&description=%@&city=%@", lEventTitle, lEventDesc, lEventCity]; 
    NSString *clearPost = [postString 
            stringByReplacingOccurrencesOfString:@"var=" withString:@""]; 
    NSLog(@"%@", clearPost); 
    [request setHTTPBody:[clearPost dataUsingEncoding:NSUTF8StringEncoding]]; 
    [request setValue:clearPost forHTTPHeaderField:@"Content-Length"]; 
    [NSURLConnection connectionWithRequest:request delegate:self]; 
    NSLog(@"%@", request); 
} 

Kiedy NSLog ciąg clearPost (string zawierający zmienne należy przesłać do serwera), to pokazuje:

title=xmas&description=Celebration&city=NY 

na koniec PHP, mam proste:

<?php 
$title = $_POST['title']; 
$description = $_POST['description']; 
$city = $_POST['city']; 

echo "Title: ". $title; 
echo "Description: ". $description; 
echo "City: ". $city; 
?> 

Po prostu próbuję uzyskać dane na PHP, aby później móc nim manipulować. Teraz, gdy wykonuję

domain.com/ios/form.php, pokazuje tytuł, opis i miasto puste.

Przepraszam, ale jestem bardzo nowy w iOS i Objective-C.

+0

1. A jakie jest pytanie? 2. Dodajesz część 'name =' dwa razy do każdej zmiennej POSTed: raz w pierwszych trzech liniach swojej metody, a następnie podczas tworzenia 'postString'. –

+0

Zmienione pytania zostały zmienione –

+0

IOS 9 wprowadził ATS i nie zezwala na normalne żądania HTTP bez umieszczenia ich na białej liście. Kredyt: (http://stackoverflow.com/a/30732693/6042879) –

Odpowiedz

15

Objective C

// Create your request string with parameter name as defined in PHP file 
NSString *myRequestString = [NSString stringWithFormat:@"title=%@&description=%@&city=%@",eventTitle.text,eventDescription.text,eventCity.text]; 

// Create Data from request 
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]]; 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http://www.youardomain.com/phpfilename.php"]]; 
// set Request Type 
[request setHTTPMethod: @"POST"]; 
// Set content-type 
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"]; 
// Set Request Body 
[request setHTTPBody: myRequestData]; 
// Now send a request and get Response 
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil]; 
// Log Response 
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding]; 
NSLog(@"%@",response); 

Swift

// Create your request string with parameter name as defined in PHP file 
var myRequestString: String = "title=\(eventTitle.text!)&description=\(eventDescription.text!)&city=\(eventCity.text!)" 
// Create Data from request 
var myRequestData: NSData = NSData.dataWithBytes(myRequestString.UTF8String(), length: myRequestString.characters.count) 
var request: NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: "http://www.youardomain.com/phpfilename.php")!) 
// set Request Type 
request.HTTPMethod = "POST" 
// Set content-type 
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type") 
// Set Request Body 
request.HTTPBody = myRequestData 
// Now send a request and get Response 
var returnData: NSData = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil) 
// Log Response 
var response: String = String(bytes: returnData.bytes(), length: returnData.characters.count, encoding: NSUTF8StringEncoding) 
NSLog("%@", response) 
+0

, jeśli nadal nie możesz tego zrobić dobrze, proszę zapytać. Dziękuję. –

+0

To faktycznie działało z małymi zmianami! Dziękuję koledze z zespołu –

+0

pozwól mi sprawdzić na moim serwerze php. Niedługo wrócę. –

0

Spróbuj tego:

[request setValue:[NSString stringWithFormat:@"%d",[clearPost length]] forHTTPHeaderField:@"Content-Length"]; 

ok dodaję mój kod żądania: może to być pomocne

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] 
             initWithURL:[NSURL 
                URLWithString:@"http://www.sth.com/action/verify.php"]]; 

     [request setHTTPMethod:@"POST"]; 
     [request setValue:[NSString stringWithFormat:@"%i",[sent length]] forHTTPHeaderField:@"Content-length"]; 
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
     [request setHTTPBody:[sent dataUsingEncoding:NSASCIIStringEncoding]]; 
+0

Edytowałem i próbowałem następujących rzeczy: po wprowadzeniu danych wciskam Zapisz. Następnie przejdę do chrome i wejdę na stronę domena.com/ios/form.php. Wciąż nic nie pokazuje. Czy robię to dobrze? –

+0

Czy możesz napisać Content-Type zamiast content-type – meth

2

NSURLConnection został zdepracowany od IOS 9.0. Proszę używać NSURLSesstion:

-(void) httpPostWithCustomDelegate 
{ 
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration]; 
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]]; 

NSURL * url = [NSURL URLWithString:@"http://hayageek.com/examples/jquery/ajax-post/ajax-post.php"]; 
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url]; 
NSString * params [email protected]"name=Ravi&loc=India&age=31&submit=true"; 
[urlRequest setHTTPMethod:@"POST"]; 
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]]; 

NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest 
            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
             NSLog(@"Response:%@ %@\n", response, error); 
             if(error == nil) 
             { 
              NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; 
              NSLog(@"Data = %@",text); 
             } 

            }]; 
[dataTask resume]; 

} 

reference

Powiązane problemy