2011-05-24 174 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];