简体   繁体   English

NSURLConnection委托方法

[英]NSURLConnection delegate method

I am having a hard time to find any examples for NSURLConnection delegate method implementations. 我很难找到NSURLConnection委托方法实现的任何示例。

I want to send data with a HTTP post with a button click. 我想通过点击按钮发送带有HTTP帖子的数据。 Not sure how to make a "submitting" screen and "submitted". 不确定如何制作“提交”屏幕并“提交”。 (I know how to use spinner and will use them) (我知道如何使用微调器并将使用它们)

I am using this code under a botton click action, but unable to use any delegate stuff. 我在botton点击操作下使用此代码,但无法使用任何委托内容。 Not sure how to implement them with my current set up. 不确定如何使用我当前的设置实现它们。

NSMutableURLRequest *request = 
    [[NSMutableURLRequest alloc] initWithURL:
     [NSURL URLWithString:@"http://myURL.com"]];

    [request setHTTPMethod:@"POST"];

    NSString *postString = [wait stringByAppendingString:co];

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



    [request setHTTPBody:[postString 
                          dataUsingEncoding:NSUTF8StringEncoding]];

    //[[NSURLConnection alloc] initWithRequest:request delegate:self];
    [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];


    [SVProgressHUD dismissWithSuccess:@"Submission Successful"];
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"Did Receive Response %@", response);
    responseData = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
    //NSLog(@"Did Receive Data %@", data);
    [responseData appendData:data];
}
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
    NSLog(@"Did Fail");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Did Finish");
    // Do something with responseData
}
//Connection request
 -(void)requestURL:(NSString *)strURL
    {
        // Create the request.
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:strURL]];

        // Create url connection and fire request
        NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    }


    //Delegate methods
    - (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse *)response
    {
        NSLog(@"Did Receive Response %@", response);
        responseData = [[NSMutableData alloc]init];
    }
    - (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
    {
        //NSLog(@"Did Receive Data %@", data);
        [responseData appendData:data];
    }
    - (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
    {
        NSLog(@"Did Fail");
    }
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        NSLog(@"Did Finish");
        // Do something with responseData

        NSString *strData=[[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];

        NSLog(@"Responce:%@",strData);
    }

http://codewithchris.com/tutorial-how-to-use-ios-nsurlconnection-by-example/ http://codewithchris.com/tutorial-how-to-use-ios-nsurlconnection-by-example/

in this code you will use GCD ,Activity Indicator ,UIButton Action on login button First you will call StartActivityindicator on another thread and it keeps in moving until you remove or stop the Activityindicator. 在此代码中,您将在登录按钮上使用GCD,活动指示符,UIButton操作首先,您将在另一个线程上调用StartActivityindicator并继续移动,直到您删除或停止Activityindicator。 then you will call the web service for login in GCD queue . 然后你将调用Web服务登录GCD队列。 at the time you receive response from server call main queue to update the UI. 当您从服务器调用主队列接收响应以更新UI时。

// After the interface declration 
@interface LoginViewController ()
{

NSData *responseData;
dispatch_queue_t myqueue;

}    
//Button Action 
- (IBAction)Login_Button_Action:(id)sender

{

 [NSThread detachNewThreadSelector: @selector(StartActivityindicator) toTarget:self withObject:nil];
myqueue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_group_t group=dispatch_group_create();
dispatch_group_async(group, myqueue, ^{ [self loginWebService];});
}
-(void)loginWebService
{
//Combine Both url and parameters
    NSString *UrlWithParameters = [NSString stringWithFormat:@"http://www.xxxxx.com?count=%@&user=%@&email=%@&password=%@",@"4",@"Username",s@"UserEmail",@"PAssword String"];
//Pass UrlWithParameters to NSURL
NSURL *ServiceURL =[NSURL URLWithString:UrlWithParameters];

NSMutableURLRequest *serviceRequest =[NSMutableURLRequest requestWithURL:ServiceURL];
[serviceRequest setHTTPMethod:@"POST"];

[serviceRequest setValue:@"application/json" forHTTPHeaderField:@"accept"];
[serviceRequest setValue:@"application/json" forHTTPHeaderField:@"content-type"];

//GEt Response Here
NSError *err;
NSURLResponse *response;
responseData = [NSURLConnection sendSynchronousRequest:serviceRequest returningResponse:&response error:&err];

NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSInteger code = [httpResponse statusCode];
// check status code for response from server and do RND for code if you recive anything than 200 
NSLog(@"~~~~~ Status code: %ld",(long)code);
if (code ==200)
{
 // your response is here if you call right  
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];  

 dispatch_async(dispatch_get_main_queue(),^{
       // place the code here to update UI with your received response 
        [NSThread detachNewThreadSelector: @selector(StopActivityindicator) toTarget:self withObject:nil];
        });
}
}
//Activity indicator Method to display 
- (void) StartActivityindicator
{
mySpinner.hidden = NO;
[mySpinner startAnimating];
}
- (void) StopActivityindicator
{
mySpinner.hidden = YES;
[mySpinner stopAnimating];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM