2012-03-22 26 views
0

我有一個非常簡單的代碼很大的問題。 我需要從Facebook URL獲取圖片並將其放在UIImageView上。從網絡獲取圖像到UIImageView不起作用

我不知道但不工作。 我也試過不同的鏈接(沒有Facebook的鏈接也不工作)。

-(IBAction)setUserPhoto:(id)sender{ 

    NSURL *url = [url initWithString:@"http://graph.facebook.com/100000769380612/picture?type=large"]; 
    NSData *imageData = [NSData dataWithContentsOfURL:url]; 
    UIImage *image = [UIImage imageWithData:imageData]; 

    if(image){ 

     NSLog(@"Image OK"); 

    } else if (!image) { 

      NSLog(@"Error"); 

    } 

    [userPhoto setImage:image]; 

} 

謝謝。

回答

2

你失去了一些東西在url..it包含%@,請及時與正確的琴絃

更換爲如:

https://graph.facebook.com/DoloresPark/picture?type=large 

你的URL應該像上面的一個

一些事情
-(IBAction)setUserPhoto:(id)sender{ 

     NSString *user = @"DoloresPark"; 

     NSString *urlString = [NSString 
          stringWithFormat: 
          @"http://graph.facebook.com/%@/picture?type=large",user]; 

     NSURL *url = [NSURL URLWithString:urlString]; 

     NSData *imageData = [NSData dataWithContentsOfURL:url]; 

     UIImage *image = [UIImage imageWithData:imageData]; 

    if(image){ 

     NSLog(@"Image OK"); 

    } else if (!image) { 

     NSLog(@"Error"); 

    } 

    [userPhoto setImage:image]; 

} 
+0

不,我改變了它。還有其他問題。 – Byteros 2012-03-22 12:43:52

+0

我剛剛編輯我的答案,請嘗試它,它對我的​​工作很好 – Raj 2012-03-22 12:48:40

+0

Woooow。是工作。謝謝Rajesh。 – Byteros 2012-03-23 11:07:38

5

字符串中有一個替代變量,即沒有被替換:

http://graph.facebook.com/%@/picture?type=large 

你缺少的別名(這就是錯誤我得到,如果我把這個網址在Safari)

使用

NSString *urlString = [NSString stringWithFormat:@"http://graph.facebook.com/%@/picture?type=large", replacement]; //where replacement is the string that is supposed to go there 
NSUrl *url = [NSUrl URLWithString:urlString]; 

首先嚐試在網絡瀏覽器中的URL,以確保它存在。

+0

不,對不起,我試過正確的鏈接也。 – Byteros 2012-03-22 11:06:39

+0

NSURL * url = [url initWithString:urlString];這行會導致崩潰,所以請使用NSURL * url = [NSURL URLWithString:urlString] – Raj 2012-03-22 12:52:28

+0

.. @ Rajesh,yup,我沒有注意,它是一個init方法...回答更新 – bandejapaisa 2012-03-22 15:42:56

0

的問題是,你是不是做給URL.Use的連接進行 -

NSURLRequest *request = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:@"Your URL"]];  
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self]; 

類應該實現NSURLConnectionDelegate -

使用下面的委託方法來獲取數據 -

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data; 
- (void)connectionDidFinishLoading:(NSURLConnection *)connection; 

希望它有幫助!

+0

不,這不是問題。使用NSURLRequest將執行異步請求,但dataWithContentsOfURL仍應該獲取圖像。 – Matias 2012-03-22 14:16:07

0

你有沒有試過dataWithContentsOfURL:options:error:和讀取&錯誤的任何指針?