2012-03-06 40 views
9

Tôi đang gặp khó khăn để tìm bất kỳ ví dụ nào về việc triển khai phương pháp ủy nhiệm NSURLConnection.Phương thức ủy nhiệm NSURLConnection

Tôi muốn gửi dữ liệu bằng bài đăng HTTP có nút nhấp. Không chắc chắn cách tạo màn hình "gửi" và "đã gửi". (Tôi biết cách sử dụng spinner và sẽ sử dụng chúng)

Tôi đang sử dụng mã này dưới tác vụ nhấp chuột botton, nhưng không thể sử dụng bất kỳ nội dung đại biểu nào. Không chắc chắn cách triển khai chúng với thiết lập hiện tại của tôi.

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

Trả lời

8

Bạn cần phải sử dụng giao thức NSURLConnectionDataDelegate mới.

Tôi tìm thấy một số exemples đây:

http://blog.kemalkocabiyik.com/index.php/2012/02/fetching-data-with-getpost-methods-by-using-nsurlconnection/

Và nếu bạn có thể đọc portuguese: http://www.quaddro.com.br/blog/desenvolvimento-ios/baixando-conteudo-com-nsurlconnection-e-nsurlconnectiondatadelegate-no-ios

+0

liên kết thứ hai, người portugese thực sự giúp đỡ, thậm chí tôi không hiểu protugese, cảm ơn bạn .. – 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

không chắc chắn làm thế nào để thiết lập các đại biểu, bởi vì tôi có tất cả mã bưu điện của tôi ở trên, trong - (IBAction) nộp: (id) sender – socbrian

+0

Tất cả bốn phương pháp sẽ cháy khi bạn bắt đầu kết nối URL. Điều này sẽ có trong tệp triển khai trong cùng một lớp với phương thức bắt đầu kết nối – Eric

+0

Vì vậy, câu nói của bạn để đặt mã này trong lớp gửi của tôi? khi tôi làm điều này tôi nhận được lỗi. – 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

trong mã này, bạn sẽ sử dụng GCD, Hoạt động Indicator, UIButton Action trên nút đăng nhập Trước tiên bạn sẽ Tôi gọi StartActivityindicator trên một thread khác và nó tiếp tục di chuyển cho đến khi bạn loại bỏ hoặc ngừng Activityindicator. thì bạn sẽ gọi dịch vụ web để đăng nhập trong hàng đợi GCD. tại thời điểm bạn nhận được phản hồi từ hàng đợi chính của cuộc gọi máy chủ để cập nhật giao diện người dùng.

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

xin vui lòng thêm một mô tả ngắn gọn về những gì mã này không. cũng phải mất một chút thời gian để xem xét [trả lời] –

Các vấn đề liên quan