使用网址获取图片

时间:2011-05-24 09:31:44

标签: objective-c

我希望通过从某个网址获取图片来查看图片。我想改变给定的代码..

-(void)viewWillAppear:(BOOL)animated{
        [super viewWillAppear:animated];
        UIImage *image = [[UIImage imageNamed:<#(NSString *)name#>
        NSString * mediaUrl = [[[self appDelegate]currentlySelectedBlogItem]mediaUrl];
        [[self image]setImage:[UIImage imageNamed:@"unknown.jpg"]];
        if(nil != mediaUrl){
            NSData* imageData;
            [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
            @try {
                imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:mediaUrl]];
            }
            @catch (NSException * e) {
                //Some error while downloading data
            }
            @finally {
                UIImage * imageFromImageData = [[UIImage alloc] initWithData:imageData];
                [[self image]setImage:imageFromImageData];
                [imageData release];
                [imageFromImageData release];
            }
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        }
        self.titleTextView.text = [[[self appDelegate] currentlySelectedBlogItem]title];
        self.descriptionTextView.text = [[[self appDelegate] currentlySelectedBlogItem]description]; 
    }

2 个答案:

答案 0 :(得分:0)

我使用了以下内容:

         NSString *url=[NSString stringWithFormat:@"Your URL"];
        //NSLog(@"URL=%@",url);
        UIImage *myImage=[[UIImage alloc] initWithData:[NSData UIImage *myImage=[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: url]]];
        NSLog(@"%d byte of data", [[NSData dataWithContentsOfURL: [NSURL URLWithString: url]] length]); 

        if (myImage)
        {
         //THIS CODE WILL STORE IMAGE DOCUMENT DIRECTORY
            NSString *jpegFilePath = [NSString stringWithFormat:@"%@/%@.jpg",[self pathForDocumentDirectory],[self.idOfImagesToDownload objectAtIndex:i]];
            NSData *data1 = [NSData dataWithData:UIImageJPEGRepresentation(myImage, 1.0f)];//1.0f = 100% quality
            [data1 writeToFile:jpegFilePath atomically:YES];
        }

注意:[self pathForDocumentDirectory]是返回文档目录路径的方法。

答案 1 :(得分:0)

使用此功能将为您提供解决方案

NSURL    *url  = [NSURL URLWithString:@"ENTER YOUR URL HAVING THE IMAGE"];
NSData   *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];