2013-07-03 75 views
0

嗨我有一個從網址獲取圖像的問題。即時通訊從一個網絡服務獲取這些網址,然後加載圖像1和1附加在每個網址。從url中獲取圖像爲空值

-(void)downloadMyfriendReqImage:(NSIndexPath *)path 
{ 
    if (path.row<[arrayPendingRequests count]) { 
     NSString *str=[[arrayPendingRequests objectAtIndex:path.row]valueForKey:@"USERIMAGE"]; 
     UIImage *img = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:str]]]; 

     if (img==nil) { 
      img=[UIImage imageNamed:@"placeholder.png"]; 
     } 

     [dicPendingReqImages setObject:img forKey:str]; 
     [tblFriendRequests performSelectorOnMainThread:@selector(reloadData) withObject:@"TAG_29" waitUntilDone:NO]; 
    } 
} 

這是我用來加載圖像的方式。但問題是一些圖像沒有得到。 img成爲空值。但我在android中有相同的應用程序。它完美地加載所有這些圖像。這有什麼問題..任何人都可以幫助我。

回答

0

在將其轉換爲圖像之前,檢查NSData請求的結果。可能你是從服務器獲取超時。

+0

感謝rply。如果它採取超時req爲什麼它不影響到Android的? – iDia

+0

它可能是android使用代理,反應更快?你有沒有看過NSData的內容? –

+0

@iDia使用['dataWithContentsOfURL:options:error:'],而不是'dataWithContentsOfURL'(https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference .html#// apple_ref/occ/clm/NSData/dataWithContentsOfURL:options:error :)然後你可以看一下'NSError'來發現是否出了問題,如果是的話,是什麼。 – Rob

0
-(void)downloadMyfriendReqImage:(NSIndexPath *)path 
{ 
    if (path.row<[arrayPendingRequests count]) { 
     NSString *str=[[arrayPendingRequests objectAtIndex:path.row]valueForKey:@"USERIMAGE"]; 
     //ADDED LINE 
     str=[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 

     UIImage *img = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:str]]]; 

     if (img==nil) { 
      img=[UIImage imageNamed:@"placeholder.png"]; 
     } 

     [dicPendingReqImages setObject:img forKey:str]; 
     [tblFriendRequests performSelectorOnMainThread:@selector(reloadData) withObject:@"TAG_29" waitUntilDone:NO]; 
    } 
} 

我覺得網址包含其中NSURL無法讀取空格一些字符,使其工作,你需要編碼添加到字符串,我覺得應該以這種方式工作。檢查的代碼//ADDED LINE

+0

之前添加http://,但它在我將其粘貼到瀏覽器上時起作用。它不包含任何空格或東西 – iDia

+0

我嘗試過。但仍然同樣:( – iDia

+0

嘗試將NSLog添加到URL並看到..和特殊字符也可能會產生問題.. – iphonic

0

試試這個:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
NSString *str=[[arrayPendingRequests objectAtIndex:path.row]valueForKey:@"USERIMAGE"]; 
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:str]]; 
NSURLResponse *response; 
NSError *error; 
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
if (error) { 
    // handle error 
    return; 
} 
dispatch_async(dispatch_get_main_queue(), ^{ 
    // do something with the data 
UIImage *img = [[UIImage alloc] initWithData:data]; 
}); 
});