2012-03-06 15 views
9

Tengo dificultades para encontrar ejemplos de implementaciones de NSULConnection delegate method.NSURLConnection delegate method

Deseo enviar datos con una publicación HTTP con un clic de botón. No estoy seguro de cómo hacer una pantalla de "envío" y "enviado". (Sé cómo usar spinner y los usaré)

Estoy usando este código en una acción de clic de botón, pero no puedo usar nada de delegado. No estoy seguro de cómo implementarlos con mi configuración actual.

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"]; 

Respuesta

8
+0

el segundo enlace, el portugués realmente ayuda, incluso no entiendo protuberancia, gracias .. – Bhimbim

25
- (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 
} 
+0

no está seguro de cómo configurar el delegado, porque tengo toda mi post código anterior, en - (IBAction) presentan: (id) emisor – socbrian

+0

Los cuatro métodos se disparará cuando inicia la conexión URL. Esto debería estar en el archivo de implementación en la misma clase que el método que inicia la conexión – Eric

+0

. ¿Quiere decir que debe poner este código en mi clase de envío? cuando hago esto, recibo errores. – socbrian

4
//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/

2

en este código que va a utilizar GCD, Indicador de Actividad, UIButton Acción en el botón de inicio de sesión Primero se wil Llamo a StartActivityindicator en otro hilo y sigue moviéndose hasta que elimine o detenga el Activityindicator. luego llamará al servicio web para iniciar sesión en la cola de GCD. en el momento en que recibe la respuesta de la cola principal de la llamada del servidor para actualizar la interfaz de usuario.

// 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",[email protected]"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]; 
} 
+0

por favor agregue una breve descripción de lo que hace este código. también, tome un momento para revisar [respuesta] –