我有一个使用URL显示图像的UIImageView,我有一个下载按钮,显示一个UIActionSheet,然后使用URL下载文件我想知道如何编写下载部分的代码使用NSURLConnection。
- (IBAction)DownloadClick:(id)sender {
UIActionSheet *Action = [[UIActionSheet alloc]
initWithTitle:@"Options"
delegate:self
cancelButtonTitle:@"Cancel"
destructiveButtonTitle:nil
otherButtonTitles:@"Download", nil];
[Action showInView:self.view];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) { //The Download code will go here This is where i need ur help
}
Url保存在名为“Url”的字符串中。
答案 0 :(得分:1)
利用异步请求进行图像下载。它还可以帮助您识别图像下载过程中的错误。
NSURL* url = [NSURL URLWithString:@"http://imageAddress.com"];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
NSData * data,
NSError * error) {
if (!error){
UIImage* image = [[UIImage alloc] initWithData:data];
// do whatever you want with image
}
}];
答案 1 :(得分:1)
我不认为你为此尝试了谷歌。无论如何,这是你的代码,不要忘记添加 NSURLConnectionDataDelegate ,
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0) { //The Download code will go here This is where i need ur help
//-------------------------------------------------------
NSURL *url = [NSURL URLWithString:@"your_data_url"];
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
NSLog(@"succeed...");
} else {
NSLog(@"Failed...");
}
//-------------------------------------------------------------------
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
}
答案 2 :(得分:0)
如果您需要同步下载,可以尝试以下代码:
NSURL *imageUrl = [NSURL URLWithString:@"http://site.com/imageName.ext"];
NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
UIImage *image = [[UIImage alloc] initWithData:imageData];
现在你有了一个可以使用的图像。
如果您需要异步请求,我建议您阅读NSURLConnectionDataDelegate,以帮助您处理文件下载。