使用Objective C将POST发送到Web服务器

时间:2012-08-20 20:16:09

标签: objective-c ios xcode post webserver

我有一个非常基本的内部iOS应用程序,我想将POST发送到Web服务器。你基本上有一堆按钮,根据你按下的按钮,它会向网络服务器发送一个预先定义的“消息”。

按下按钮后,它会将它们带到另一个视图,并说谢谢您选择按下的按钮。我还希望将预定义的消息发送到Web服务器,格式化然后通过电子邮件发送到静态电子邮件地址。

这就是我到目前为止所做的...我只想弄清楚发送POST的最佳方法。我的设置方式是最好的方法吗?或者有更聪明的方法吗?

很抱歉,如果它很乱,没有组织......我对iOS开发很新。

@interface DrinkViewController () {
NSString *buttonlabel;
NSString *urlEncodeUsingEncoding;
}
@end

@implementation DrinkViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

-(IBAction)selectButton:(id)sender{
    NSLog(@"Button Pressed:%d",((UIButton *)sender).tag);
    NSString *dvalue;
    switch (((UIButton *)sender).tag) {
        case 1:
            dvalue = @"Button 1";
            break;
        case 2:
            dvalue = @"Button 2";
            break;
        case 3:
            dvalue = @"Button 3";
            break;
        case 4:
            dvalue = @"Button 4";
            break;
        case 5:
            dvalue = @"Button 5";
            break;
        case 6:
            dvalue = @"Button 6";
            break;
        case 7:
            dvalue = @"Button 7";
            break;

    }
    buttonlabel = dvalue;

    [self performSegueWithIdentifier:@"selectionTransition" sender:sender];


    NSData *postData = [buttonlabel dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    NSMutableURLRequest *request =  [NSMutableURLRequest alloc];
                                    [request setURL:[NSURL URLWithString:@"http://www.abc.com/form.php"]];
                                    [request setHTTPMethod:@"POST"];
                                    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
                                    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
                                    [request setHTTPBody:postData];
    NSLog(@"POST: %@ sent to %@", buttonlabel, request);
}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"selectionTransition"]) {

        NSLog(@"%@", buttonlabel);
        // Get destination view
        DetailViewController *vc = [segue destinationViewController];

        // Pass the information to your destination view
        [vc setLabelValue:buttonlabel];
    }
}

@end

4 个答案:

答案 0 :(得分:1)

以下是您需要使用的内容:NSURLRequest,NSURLConnection,NSURLResponse,NSURL。您可能会使用另一个库,但我建议您尝试了解这些类的工作原理(因为您对此不熟悉)。

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/Reference/Reference.html

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsurlconnection_Class/Reference/Reference.html

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLResponse_Class/Reference/Reference.html

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html

以下是它的工作原理:您使用服务器URL,创建NSURLRequest,分配正确的HTTP方法(POST,GET等)和其他必要的请求标头,然后您将调用NSURLConnection来获取响应和服务器数据。

答案 1 :(得分:0)

我的建议是使用第三方库。它将大大简化您的过程,为您节省大量时间。我通常使用AFNetworking库。

https://github.com/AFNetworking/AFNetworking

这里有一个POST示例:

http://www.6foot3foot.com/developer-journal/afnetworking-php

答案 2 :(得分:0)

结帐this post。我写了一个使用AFNetworking(我最喜欢的第三方库)的NetworkClient类。这非常灵活,可随意修改以满足您的需求。

答案 3 :(得分:0)

到目前为止,我还没有专家,但我确实在我的代码中进行网络调用。我选择了MKNetworkKit来替换我抱歉的网络代码。

以下是您在项目中如何使用它的示例:

- (void)myFunctionToSendDataToTheServer
{
    /*
     *  So here is a basic idea of how you could quickly use MKNetworkKit.
     *  the [op addData:postData forKey:@"postDataKey"]; call is where you're
     *  add that post data to the request body.
     */
    NSString *someVariableYouWantPosted;
    NSData *postData = [someVariableYouWantPosted dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:@"abc.com"];

    MKNetworkOperation *op = [engine operationWithPath:@"/form.php"];
    [op addData:postData forKey:@"postDataKey"];

    /*
     *  If you're not familiar with blocks then this "onCompletion^" might look weird.
     *  Inside of the curly braces will get called when the request is done.
     */

    [op onCompletion:^(MKNetworkOperation *completedOperation) {
        NSLog(@"Successful response from server: %@", [completedOperation responseString]);

        /*
         *  There are also some nice helper methods for extracting the response data in a different form
         *  [completedOperation responseJSON];
         *  [completedOperation responseImage];
         *  [completedOperation responseData];
         */

    } onError:^(NSError *error) {
        if ([error code] == kCFURLErrorNotConnectedToInternet) {
            /*
             *  Maybe retry? 
             *  This network kit also comes with a "freezable" property on the MKNetworkOperation.
             *  If you set that to YES then you don't need to worry about internet connectivity,
             *  the kit will try to send later when it reconnects.
             */
        }
        else {
            /*
             *  You'll have your work cut out for you here. Sourcing the problem can be difficult.
             *  Simply an alert message or loggin the NSError to find out where you went wrong.
             */
        }

    }];

    /*
     * Don't forget to call "enqueueOperation:".
     *  This actually gets the request going and sends it off to the server.
     */

    [engine enqueueOperation:op];
}

如果您对此主题有任何其他问题或者我不清楚,请告诉我。