2011-05-24 74 views
0

我希望通过从某个url获取图像来查看图像。我想在给定的代码改变..通过使用url获取图像

-(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]; 
    } 
+0

@ user766063大家好,欢迎。您可以通过选择代码来格式化源代码,然后单击{}按钮。给定的代码有什么问题? – 2011-05-24 09:35:20

+0

上面的代码的问题是,它阻止你的用户界面,所以图像请求绝对不应该在viewWillAppear方法。我会在后台启动选择器,然后在下载图像时通知主线程。 – Dmytro 2011-05-24 09:50:27

回答

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]; 
     } 

注:自pathForDocumentDirectory]是方法返回的文件目录的路径。

+0

@马修弗雷德里克:D – rptwsthi 2011-05-24 10:40:22

0

使用这会给你的计算器解决

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