发送请求IOS 7

时间:2014-01-19 06:40:39

标签: ios http post

好吧我一直在努力适应目标C而且它对我来说是一个过山车,无论如何我只是想向服务器发送一个简单的帖子请求,但它看起来并不像它那样简单机器人。目前我有以下方法:

-(void)postMethod
{

    [self.connection cancel];

    //initialize new mutable data
    NSMutableData *data = [[NSMutableData alloc] init];
    self.receivedData = data;

    //initialize url that is going to be fetched.
    NSURL *url = [NSURL URLWithString:@"http://blank.com/register.php"];

    //initialize a request from url
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];

    //set http method
    [request setHTTPMethod:@"POST"];
    //initialize a post data
    NSString *postData = @"username=postTest&displayname=testingPoster&password=postest&passwordc=postest&email=posttesting%40posttest.com&bio=I+am+tesring+the+post+test&skills=I+am+a+hacka&interests=hacing+and+cracking&skills_needed=some+php+skills&company=Post+testing+the+script&dob=naaaaaa&occupation=Qoekkk";
    //Here you can give your parameters value

    //set request content type we MUST set this value.

    [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    //set post data of request
    [request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];

    //initialize a connection from request
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    self.connection = connection;


    //start the connection
    [connection start];
}

我有一个按钮来调用该函数:

- (IBAction)register:(id)sender {

    [self postMethod];


}

我确实在我的头文件中包含NSURLConnectionDataDelegate,但是当我单击按钮时尝试发送请求时,它没有通过它只是停止程序,它没有任何错误。任何建议,我一直在网上搜索只是为了学习如何发送帖子请求,我认为这不应该是非常困难的。

只是因为重要,我正在使用ios 7的最新iphone sdk。

2 个答案:

答案 0 :(得分:3)

请注意,对于iOS 7,建议使用NSURLSession。 NSURLConnection可能会在将来的版本中弃用。您可以使用三种URL session tasks中的任何一种来发出POST请求。 NSURLSessionDataTask几乎等同于NSURLConnection。即使应用程序被挂起或崩溃,NSURLSessionUploadTaskNSURLSessionDownloadTask(将接收的数据写入磁盘)也可以在后台会话中使用并继续(在另一个进程中)。可以在this guide中阅读更多内容。

答案 1 :(得分:1)

AFNetworking经过了测试和测试。 - 查看下面的例子,它也使用基本身份验证:

- (void)postToAPI   {

    NSURL *postURL = [NSURL URLWithString:@"http://yourdomain.com/api/operation"];

    AFHTTPClient* httpClient = [AFHTTPClient clientWithBaseURL:postURL];
    httpClient.parameterEncoding = AFJSONParameterEncoding;
    [httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
    [httpClient setDefaultHeader:@"Accept" value:@"application/json"];

    // Set up authentication - Get username from keychain
    KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"bnmcred" accessGroup:nil];
    NSString *password = [keychainItem objectForKey:(__bridge id)kSecValueData];
    NSString *username = [keychainItem objectForKey:(__bridge id)kSecAttrAccount];

    [httpClient setAuthorizationHeaderWithUsername:username password:password];

    // Create Post Dictionary
    NSMutableDictionary* postRequestDictionary = [[NSMutableDictionary alloc] init];
    postRequestDictionary[@"your_post_item_1"] = @"Hello";
    postRequestDictionary[@"your_post_item_2"] = @"World";

    // Create Request
    NSMutableURLRequest* request = [httpClient requestWithMethod:@"POST" path:nil parameters:postRequestDictionary];

    self.httpOperation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        NSLog(@"Success");

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"Failure with error:%@", error);
    }];

    [self.httpOperation start];
}