Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone
 

Registered : 109,027

HOME > Mobile > [iOS/iPhone] Tutorials - สอนเขียน iPhone App ฟรี เขียน iPad App เรียน iPhone เขียนโปรแกรม iPhone > iOS/iPhone NSURLConnection Show Progress and Activity Indicator View (UIActivityIndicatorView)



Clound SSD Virtual Server

iOS/iPhone NSURLConnection Show Progress and Activity Indicator View (UIActivityIndicatorView)

iOS/iPhone NSURLConnection Show Progress and Activity Indicator View (UIActivityIndicatorView) ปกติแล้วการทำงานระหว่าง Client กับ Server อาจจะใช้เวลาซะพักหนึ่งในการเชื่อมต่อ และได้ข้อมูลกลับมา และในระหว่างที่รอนี้เราสามารถใช้ Activity Indicator View (Icons หมุ่น ๆ) แสดงสถานะการทำงาน เหตุผลที่ใช้ Activity Indicator View (UIActivityIndicatorView) เพราะเป็น Icons แสดงสถานะที่ไม่ทราบเวลาการทำงานที่แท้จริง แต่จะทำงานไปเรื่อย ๆ จนกว่าจะเสร็จ หรือหมดเวลาที่กำหนดไว้

iOS/iPhone NSURLConnection Show Progress and Activity Indicator View (UIActivityIndicatorView)

iOS/iPhone NSURLConnection Show Progress and Activity Indicator View (UIActivityIndicatorView)


โดย Activity Indicator View (UIActivityIndicatorView) เราสามารถใช้งานร่วมกับ Popup หรือ Alert View (UIAlertView) เพื่อแสดงสถานะการทำงานบน Popup ได้เช่นเดียวกัน สามารถอ่านได้ที่บทความนี้

iOS/iPhone Activity Indicator View and AlertView (UIAlertView / UIActivityIndicatorView)


และการใช้งาน Activity Indicator View (UIActivityIndicatorView) ร่วมกับ NSURLConnection นั้นเราสามารถแทรกคำสั่งให้ Alert View ทำงานได้จาก delegate method ของ NSURLConnection ซึ่งจะ method ที่แจ้งสถานะต่าง ๆ เช่น ในขณะที่กำลังทำงานก็ให้ Alert View ทำงาน และหลังจากที่ทำงานเรียบร้อยแล้ว ก็ให้ Alert View ซ่อน ลองมาดูตัวอย่าง

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    NSURLRequest *theRequest =
    [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.thaicreate.com/url/getGallery.php"]
                     cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                 timeoutInterval:10.0];
    
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    
    // Loading Show Alert View...
    loading = [[UIAlertView alloc] initWithTitle:@"" message:@"Please Wait..." delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    UIActivityIndicatorView *progress= [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125, 50, 30, 30)];
    progress.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    [loading addSubview:progress];
    [progress startAnimating];
    [progress release];
    [loading show];
    

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    receivedData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if(receivedData)
    {
	// Hide Alert View
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        [loading dismissWithClickedButtonIndex:0 animated:YES];
    }
}

การใช้งาน Activity Indicator View (UIActivityIndicatorView) ร่วมกับ NSURLConnection ผ่าน delegate method ต่าง ๆ

เพิ่มเติม
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

ตัวนี้แสดง Icons หมุ่นเล็ก ๆ มุมซ้ายของเครื่อง Smart Phone








อ่านเพิ่มเติม delegate method ของ NSURLConnection (Objective-C)

ตัวอย่างนี้เขียนต่อจากบทความนี้ iOS/iPhone NSURLConnection and PHP MySQL / JSON


iOS/iPhone NSURLConnection Show Progress and Activity Indicator View (UIActivityIndicatorView)

Table View ที่ได้ออกแบบไว้ จากตัวอย่างก่อนหน้านี้ ให้แก้ไข Code เป็นดังนี้

ViewController.h
//
//  ViewController.h
//  NSURLConnectioJSON
//
//  Created by Weerachai on 12/8/55 BE.
//  Copyright (c) 2555 Weerachai. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDataSource,UITableViewDelegate>
{
    
    IBOutlet UITableView *myTable;
    
}

@property(nonatomic,assign) NSMutableData *receivedData;

@end


ViewController.m
//
//  ViewController.m
//  NSURLConnectioJSON
//
//  Created by Weerachai on 12/8/55 BE.
//  Copyright (c) 2555 Weerachai. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
{
    NSMutableArray *myObject;
    
    // A dictionary object
    NSDictionary *dict;
    
    // Define keys
    NSString *galleryid;
    NSString *name;
    NSString *titlename;
    NSString *thumbnail;
    
    UIAlertView *loading;
}

@end

@implementation ViewController

@synthesize receivedData;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    // Show Network IndicatorV
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    
    // Define keys
    galleryid = @"GalleryID";
    name = @"Name";
    titlename = @"TitleName";
    thumbnail = @"Thumbnail";
    
    // Create array to hold dictionaries
    myObject = [[NSMutableArray alloc] init];
    
    
    NSURLRequest *theRequest =
    [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.thaicreate.com/url/getGallery.php"]
                     cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                 timeoutInterval:10.0];
    
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    
    // Loading...
    loading = [[UIAlertView alloc] initWithTitle:@"" message:@"Please Wait..." delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    UIActivityIndicatorView *progress= [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125, 50, 30, 30)];
    progress.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    [loading addSubview:progress];
    [progress startAnimating];
    [progress release];
    [loading show];
    
    
    if (theConnection) {
        self.receivedData = nil;
    } else {
		UIAlertView *connectFailMessage = [[UIAlertView alloc] initWithTitle:@"NSURLConnection " message:@"Failed in viewDidLoad"  delegate: self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
		[connectFailMessage show];
		[connectFailMessage release];
    }
    
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    receivedData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    
    [connection release];
    [receivedData release];
    
    // inform the user
    UIAlertView *didFailWithErrorMessage = [[UIAlertView alloc] initWithTitle: @"NSURLConnection " message: @"didFailWithError"  delegate: self cancelButtonTitle: @"Ok" otherButtonTitles: nil];
    [didFailWithErrorMessage show];
    [didFailWithErrorMessage release];
	
    //inform the user
    NSLog(@"Connection failed! Error - %@", [error localizedDescription]);
    
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if(receivedData)
    {
        //NSLog(@"%@",receivedData);
        //NSString *dataString = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
        //NSLog(@"%@",dataString);
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        [loading dismissWithClickedButtonIndex:0 animated:YES];
        
        id jsonObjects = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:nil];
        
        // values in foreach loop
        for (NSDictionary *dataDict in jsonObjects) {
            NSString *strGalleryID = [dataDict objectForKey:@"GalleryID"];
            NSString *strName = [dataDict objectForKey:@"Name"];
            NSString *strTitleName = [dataDict objectForKey:@"TitleName"];
            NSString *strThumbnail = [dataDict objectForKey:@"Thumbnail"];
            
            dict = [NSDictionary dictionaryWithObjectsAndKeys:
                    strGalleryID, galleryid,
                    strName, name,
                    strTitleName, titlename,
                    strThumbnail, thumbnail,
                    nil];
            [myObject addObject:dict];
        }
    
        [myTable reloadData];
    }
    
    
    // release the connection, and the data object
    [connection release];
    [receivedData release];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    int nbCount = [myObject count];
    if (nbCount == 0)
        return 1;
    else
        return [myObject count];
 
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    int nbCount = [myObject count];
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        // Use the default cell style.
        cell = [[[UITableViewCell alloc] initWithStyle : UITableViewCellStyleSubtitle
                                       reuseIdentifier : CellIdentifier] autorelease];
    }
    
    if (nbCount ==0)
        cell.textLabel.text = @"Loading...";
    else
    {
        NSDictionary *tmpDict = [myObject objectAtIndex:indexPath.row];
        
        NSURL *url = [NSURL URLWithString:[tmpDict objectForKey:thumbnail]];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *img = [[UIImage alloc] initWithData:data];
        cell.imageView.image = img;
        
        cell.textLabel.text = [tmpDict objectForKey:name];
        cell.detailTextLabel.text= [tmpDict objectForKey:titlename];
    }
    
    //[tmpDict objectForKey:galleryid]
    //[tmpDict objectForKey:name]
    //[tmpDict objectForKey:titlename]
    //[tmpDict objectForKey:thumbnail]
    
    return cell;
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [myTable release];
    [super dealloc];
}
@end









Screenshot

iOS/iPhone NSURLConnection Show Progress and Activity Indicator View (UIActivityIndicatorView)

แสดง UIActivityIndicatorView ในขณะที่กำลังโหลดข้อมูล

iOS/iPhone NSURLConnection Show Progress and Activity Indicator View (UIActivityIndicatorView)

หลังจากที่แสดงข้อมูลเรียบร้อยแล้ว Progress ก็จะหายไป

   
Share


ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท


ลองใช้ค้นหาข้อมูล


   


Bookmark.   
       
  By : ThaiCreate.Com Team (บทความเป็นลิขสิทธิ์ของเว็บไทยครีเอทห้ามนำเผยแพร่ ณ เว็บไซต์อื่น ๆ)
  Score Rating :  
  Create/Update Date : 2012-12-13 12:26:32 / 2017-03-26 08:56:56
  Download : Download  iOS/iPhone NSURLConnection Show Progress and Activity Indicator View (UIActivityIndicatorView)
 Sponsored Links / Related

 
iOS/iPhone Activity Indicator View and AlertView (UIAlertView / UIActivityIndicatorView)
Rating :

 
iOS/iPhone Activity Indicator View (ActivityIndicator,UIActivityIndicatorView) Example (iPhone,iPad)
Rating :

 
iOS/iPhone Progress View (UIProgressView) Example (iPhone,iPad)
Rating :

 
iOS/iPhone Web View (UIWebView) Open Web Site and HTML (Objective-C, iPhone, iPad)
Rating :

 
iOS/iPhone Get the String contents from URL (Website)
Rating :

 
iOS/iPhone Image URL Display an Image from URL (Website)
Rating :

 
iOS/iPhone Display Image on Table View from JSON URL (Web Site)
Rating :

 
iOS/iPhone NSURLConnection (Objective-C)
Rating :

 
iOS/iPhone Image View and NSURLConnection ActivityIndicator Progress
Rating :

 
iOS/iPhone NSURLRequest Example (Objective-C)
Rating :

 
iOS/iPhone NSURLConnection POST Method and Send Parameter (Objective-C)
Rating :

 
iOS/iPhone NSMutableURLRequest Example (Objective-C)
Rating :

 
iOS/iPhone NSURLConnection and PHP MySQL / JSON (TableView,UITableView)
Rating :


ThaiCreate.Com Forum


Comunity Forum Free Web Script
Jobs Freelance Free Uploads
Free Web Hosting Free Tools

สอน PHP ผ่าน Youtube ฟรี
สอน Android การเขียนโปรแกรม Android
สอน Windows Phone การเขียนโปรแกรม Windows Phone 7 และ 8
สอน iOS การเขียนโปรแกรม iPhone, iPad
สอน Java การเขียนโปรแกรม ภาษา Java
สอน Java GUI การเขียนโปรแกรม ภาษา Java GUI
สอน JSP การเขียนโปรแกรม ภาษา Java
สอน jQuery การเขียนโปรแกรม ภาษา jQuery
สอน .Net การเขียนโปรแกรม ภาษา .Net
Free Tutorial
สอน Google Maps Api
สอน Windows Service
สอน Entity Framework
สอน Android
สอน Java เขียน Java
Java GUI Swing
สอน JSP (Web App)
iOS (iPhone,iPad)
Windows Phone
Windows Azure
Windows Store
Laravel Framework
Yii PHP Framework
สอน jQuery
สอน jQuery กับ Ajax
สอน PHP OOP (Vdo)
Ajax Tutorials
SQL Tutorials
สอน SQL (Part 2)
JavaScript Tutorial
Javascript Tips
VBScript Tutorial
VBScript Validation
Microsoft Access
MySQL Tutorials
-- Stored Procedure
MariaDB Database
SQL Server Tutorial
SQL Server 2005
SQL Server 2008
SQL Server 2012
-- Stored Procedure
Oracle Database
-- Stored Procedure
SVN (Subversion)
แนวทางการทำ SEO
ปรับแต่งเว็บให้โหลดเร็ว


Hit Link
   







Load balance : Server 02
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่