非同步傳輸取得網路資料, 透過請求方式等待server回傳資料

此範例為將接收到的資料顯示於UIImageView上, 並且透過Button點擊事件觸發非同步傳輸與顯示圖片事件

非同步傳輸可避免取得資料會有稍微停頓之問題

 

/*ViewController.h*/

#import <UIKit/UIKit.h> 

@interface ViewController : UIViewController

<NSURLConnectionDelegate, NSURLConnectionDataDelegate>

{

    NSMutableData *returnData;

}

@property (weak, nonatomic) IBOutletUIImageView *myImageViw;

@end

 

 /*ViewController.m*/

#import "ViewController.h"

@interfaceViewController ()

@end 

@implementation ViewController 

- (IBAction)getDataBtnClick:(id)sender {

    /*儲存欲取得之路徑並指定給urlString*/

    NSString *urlString = @"http://mobiledev.tw/wp-content/uploads/2013/01/2013-04-08-14.22.02-1024x576.jpg";

 

    /*建立NSURL request物件設定請求內容*/

   NSURLRequest *request =

   [NSURLRequestrequestWithURL:[NSURLURLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
                                                    cachePolicy:NSURLRequestReloadIgnoringCacheDatatimeoutInterval:60.0f];

 

    /*An NSURLConnection may be used for loading  of resource data directly to memory*/

    NSURLConnection *theConnection = [NSURLConnectionconnectionWithRequest:request delegate:self];

    if (theConnection) {
        returnData = [NSMutableDatadata]; //進行初始化
    }else{
        NSLog(@"error");
    } 
}

/*若收到錯誤把資料清空*/

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

{
    returnData = nil;
}

/*有收到respone印出log*/

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{
    NSLog(@"receive  respone");
}

/*取得data資料*/

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{
    [returnDataappendData:data];
}

/*所有資料拿到手設定imageView*/

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{
    _myImageViw.image=[UIImageimageWithData:returnData];
} 

@end

arrow
arrow
    文章標籤
    iOS 非同步傳輸 objectiveC
    全站熱搜

    Will 發表在 痞客邦 留言(0) 人氣()