Mac开发学习_2
URL文件下载
1 打开XCode 新建一个工程UrlDownloader
2 打开MainMenu.xib 在视图上添加一个NSTextField,用于输入url地址
再创建一个NSButton下载按钮

3 创建一个DownloadController文件
编码如下:
//
// DownloadController.h
// UrlDownloader
//
// Created by Rogo on 4/20/12.
// Copyright (c) 2012 Rogo.com. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface DownloadController : NSObject <NSURLDownloadDelegate>
{
IBOutlet NSTextField *textField;
IBOutlet NSButton *downloadButton;
}
- (IBAction)startDownloadingURL:(id)sender;
@end
//
// DownloadController.m
// UrlDownloader
//
// Created by Rogo on 4/20/12.
// Copyright (c) 2012 Rogo.com. All rights reserved.
//
#import "DownloadController.h"
@implementation DownloadController
- (void)startDownloadingURL:sender
{
NSURL *url = [NSURL URLWithString:[textField stringValue]];
NSLog(@"Start download URL: %@", [url absoluteString]);
// Create a url request
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
// The download starts immediately upon receiving the
// initWithRequest:delegate: message
NSURLDownload *theDownload = [[NSURLDownload alloc] initWithRequest:theRequest
delegate:self];
if (theDownload)
{
}
}
- (void)downloadDidBegin:(NSURLDownload *)download
{
NSLog(@"download begin");
}
- (void)download:(NSURLDownload *)download decideDestinationWithSuggestedFilename:(NSString *)filename
{
NSString *destinationFilename;
NSString *homeDirectory = NSHomeDirectory();
destinationFilename = [[homeDirectory stringByAppendingPathComponent:@"Desktop"]
stringByAppendingPathComponent:filename];
[download setDestination:destinationFilename allowOverwrite:NO];
NSLog(@"Destination Filename: %@", destinationFilename);
}
- (void)downloadDidFinish:(NSURLDownload *)download
{
NSLog(@"download finish");
}
- (void)download:(NSURLDownload *)download didFailWithError:(NSError *)error
{
NSLog(@"downoad error");
}
@end
4 打开MainMenu.xib,拖拽一个新的NSObject对象,选中该对象,打开indentity inspector面板,将Class 指向到刚刚创建的DownloadController类

5 将视图与代码关联

6 保存工程 编译运行,输入要下载文件的地址下载,文件就下载到桌面了

By Rogo [coco]
posted on 2012-04-20 21:48 Rogo_s_Blog 阅读(368) 评论(0) 收藏 举报
浙公网安备 33010602011771号