2012-03-22 24 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:和读取&错误的任何指针?