Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

cocoa touch - iPhone: Post data to php page

Despite looking at similar posts on this site and google, I just can't wrap my head around how to post to a php page from the iPhone. Here is what I want to do:

I have a php script, say at www.mypage.com/myscript.php that I could post to normally by doing www.mypage.com/myscript.php?mynumber=99&myname=codezy

This in turn will add a log message in database for example. I do not want any data back, it is essentially a one way transaction. NSMutableURLRequest seems to be what I am looking for but I just cant get a handle on how to make this work with a couple parameters.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you're sending a single URL request without needing to send multiple variations, NSURLRequest will do. Even though you are using multiple parameters, they are all part of the same URL, so you just treat them that way. Build the URL as a string first and then use the string to initialize a NSURL object.

You are prompting a log message on the server, but you will want to have response data in case something goes wrong. You can just ignore the response data unless there's an error. The request is sent using a NSURLConnection object.

NSURL *urlToSend = [[NSURL alloc] initWithString: @"www.mypage.com/myscript.php?mynumber=99&myname=codezy"];

NSURLRequest *urlRequest = [NSURLRequest requestWithURL:urlToSend   
                                            cachePolicy:NSURLRequestReturnCacheDataElseLoad                                               
                                   cachetimeoutInterval:30];

NSData *urlData;
NSURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest  
                                returningResponse:&response 
                                            error:&error];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...