0

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

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

这就是我到目前为止所拥有的......我只是想找出发送 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

4 回答 4

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 来获取响应和服务器数据。

于 2012-08-20T21:01:11.417 回答
0

我的建议是使用 3rd 方库。它将大大简化您的流程并为您节省大量时间。我通常使用 AFNetworking 库。

https://github.com/AFNetworking/AFNetworking

这里有一个 POST 示例:

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

于 2012-08-20T20:53:56.587 回答
0

看看这篇文章。我编写了一个使用 AFNetworking(我最喜欢的第 3 方库)的 NetworkClient 类。这非常灵活,可以随意修改以满足您的需求。

于 2012-08-20T20:59:14.247 回答
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];
}

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

于 2012-08-20T21:58:52.053 回答