IOS中通過URL地址下載相應地址的資源的實現。

來源:互聯網
上載者:User

這次主要說的是,通過指定相應的URL地址,通過發送請求,建立串連,並下載資料的過程,為了更好的理解,我們只實現這個過程,而不去關心下載了什麼內容,對於下載的內容我們也暫時不作處理,留待以後解決。首先我們應該建立一個空視圖的工程。然後在進行編碼,發送請求有兩種方式,同步請求和非同步請求,在日常生活中非同步請求要比同步請求更加的常見。所以我們先說一下非同步請求。

代碼如下:

HHLAppDelegate.h


#import @interface BoAppDelegate : UIResponder @property (strong, nonatomic) UIWindow *window;@property (retain, nonatomic) NSMutableData *pData;@end

HHLAppDelegate.m

#import "BoAppDelegate.h"#define URL @"http://www.baidu.com"@implementation BoAppDelegate- (void)dealloc{    [_window release];    [_pData release];    [super dealloc];}- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];    // Override point for customization after application launch.    self.window.backgroundColor = [UIColor whiteColor];        /*非同步請求*/    //1.擷取網路資源路徑(URL)    NSURL *pURL1 = [NSURL URLWithString:URL];    //2.根據URL建立請求    NSURLRequest *pRequset1 = [NSURLRequest requestWithURL:pURL1 cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];    //3.(與同步請求的區別點)發起請求,通過委託模式回調完成資料擷取    [NSURLConnection connectionWithRequest:pRequset1 delegate:self];        [self.window makeKeyAndVisible];    return YES;}#pragma mark  URLConnectionDataDelegate//1.伺服器響應回調的方法- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{    NSLog(@"伺服器響應");    self.pData = [NSMutableData dataWithCapacity:5000];}//2.服務返回資料,用戶端開始接受(data為返回的資料)- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{    NSLog(@"伺服器返回資料");    //將返回資料放入緩衝區    [self.pData appendData:data];}//3.資料接受完畢回調的方法- (void)connectionDidFinishLoading:(NSURLConnection *)connection{    NSLog(@"資料接受完畢");    NSLog(@"pData = %@",self.pData);}//4.接受資料失敗時候調用的方法- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{    NSLog(@"資料接受失敗,失敗原因:%@",[error localizedDescription]);}- (void)applicationWillResignActive:(UIApplication *)application{    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.}- (void)applicationDidEnterBackground:(UIApplication *)application{    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.}- (void)applicationWillEnterForeground:(UIApplication *)application{    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.}- (void)applicationDidBecomeActive:(UIApplication *)application{    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.}- (void)applicationWillTerminate:(UIApplication *)application{    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.}@end

運行後的結果如下:

下面的就是下載下來的資料,由於還沒有進行處理,所以看起來就是這樣


<喎?http://www.bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+Cs2ssr3Ktc/Wz8LU2Lj60uyyvda709C63MnZ0ruyv7fW09Cy7rHwo6y+zcrH1NpISExBcHBEZWxlZ2F0ZS5t1tA8L3A+CjxwPgrI58/Co7o8L3A+CjxwPgo8YnI+CjwvcD4KPHA+PC9wPgo8cHJlIGNsYXNzPQ=="brush:java;">

#import "BoAppDelegate.h"#define URL @"http://www.baidu.com"@implementation BoAppDelegate- (void)dealloc{    [_window release];    [_pData release];    [super dealloc];}- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];    // Override point for customization after application launch.    self.window.backgroundColor = [UIColor whiteColor];    //同步請求    //第一步:URL    NSURL *pURL = [NSURL URLWithString:URL];    //第二步:建立一個請求    NSURLRequest *pRequest = [NSURLRequest requestWithURL:pURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];        //第三步:建立串連    NSError *pError = nil;    NSURLResponse *pRespond = nil;    //向伺服器發起請求(發起之後,線程就會一直等待伺服器響應,直到超出最大回應時間)    NSData *pData = [NSURLConnection sendSynchronousRequest:pRequest returningResponse:&pRespond error:&pError];        NSLog(@"pData = %@",pData);    NSLog(@"pError = %@",[pError localizedDescription]);         //    /*非同步請求*///    //1.擷取網路資源路徑(URL)//    NSURL *pURL1 = [NSURL URLWithString:URL];//    //2.根據URL建立請求//    NSURLRequest *pRequset1 = [NSURLRequest requestWithURL:pURL1 cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];//    //3.(與同步請求的區別點)發起請求,通過委託模式回調完成資料擷取//    [NSURLConnection connectionWithRequest:pRequset1 delegate:self];        [self.window makeKeyAndVisible];    return YES;}- (void)applicationWillResignActive:(UIApplication *)application{    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.}- (void)applicationDidEnterBackground:(UIApplication *)application{    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.}- (void)applicationWillEnterForeground:(UIApplication *)application{    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.}- (void)applicationDidBecomeActive:(UIApplication *)application{    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.}- (void)applicationWillTerminate:(UIApplication *)application{    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.}@end


效果跟上面非同步實現下載的下過差不多,就不了,這裡主要實現的下載的功能,對於資料沒有處理,希望大家能夠見諒哦。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.