2012-04-02 2 views
0

Я следую iOS 5 учебной книжкой [Newsstand Chapter], но у меня проблема с обновлением значка.Обновление значка в прессе

Как я знаю, рамки для газетных киосков имеют функцию загрузки содержимого из URL-адреса и сохранения его в каталоге приложения, например, приложение погоды прекращено или нет, этот метод должен работать, верно?

1 Заявки скачать только значок с моего сайта, в то время как приложение работает в фоновом режиме 2 После загрузки файла иконка, приложение должно заменить мою новую иконку с текущим значком, который вместе с нажимным уведомлением

вот мой код, но ничего не происходит !! где я должен поместить эту строку кода? в моем appDelegate или AppViewController?

- (void)connectionDidFinishDownloading:(NSURLConnection*)connection destinationURL:(NSURL*)destinationURL { 

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    [self saveFile:@"NSIcon" ofType:@"png" fromURL:@"http://website.com/NSIcon.png" inDirectory:documentsDirectory]; 



UIImage * newsstandImage = [self loadImage:@"NSIcon" ofType:@"png" inDirectory:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]]; 

    UIApplication *app = [UIApplication sharedApplication]; 
    [app setNewsstandIconImage:newsstandImage]; 

    NSLog(@"downloading..."); 

} 

код примера слишком запутан! с большим количеством кодов и пользовательскими классами или делегатами, я был бы признателен за помощь мне решить эту проблему

Спасибо

Редакция:

#pragma mark ViewDidLoad 
- (void)viewDidLoad 
{ 


    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://website.com/NSIcon.png"]]; 
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
    if(conn){ 
     webData = [NSMutableData data]; 

     UIApplication *indicator = [UIApplication sharedApplication]; 
     indicator.networkActivityIndicatorVisible = YES; 

     NSLog(@"%@",webData); 
    } 

} 





#pragma mark NewsStand Methods 
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response 
{ 

[webData setLength:0]; 
} 


-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data 
{ 
    NSLog(@"Download Finish"); 

    UIApplication *indicator = [UIApplication sharedApplication]; 
    indicator.networkActivityIndicatorVisible = NO; 

    [webData appendData:data]; 
} 


-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error 
{ 
    // inform the user if connection fails// 
    NSLog(@"Connection failed! Error - %@ %@",[error localizedDescription],[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); 



} 



- (void)connectionDidFinishDownloading:(NSURLConnection*)connection destinationURL:(NSURL*)destinationURL { 

    UIApplication *indicator = [UIApplication sharedApplication]; 
    indicator.networkActivityIndicatorVisible = NO; 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    [self saveFile:@"NSIcon" ofType:@"png" fromURL:@"http://website.com/NSIcon.png" inDirectory:documentsDirectory]; 

    UIImage * newsstandImage = [self loadImage:@"NSIcon" ofType:@"png" inDirectory:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]]; 

    UIApplication *app = [UIApplication sharedApplication]; 
    [app setNewsstandIconImage:newsstandImage]; 

    NSLog(@"downloading..."); 

} 

2012-04-03 23:35 : 11,297 IMAG [6757: 15803] - [__ NSCFDictionary SetLength]: непризнанные селектор направлен например 0x85acfd0 (lldb)

+0

Вы спрашиваете, где вы должны поставить эту функцию. Также вы понимаете, как работает эта функция? "- (void) connectionDidFinishDownloading: (NSURLConnection *) connection destinationURL: (NSURL *) destinationURL;"? –

ответ

1

connectionDidfinishDownloading вызывается, когда вы создаете соединение. Пример:

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
    if(conn){ 
     webData = [NSMutableData data]; 
     [Loading startAnimating]; 

     NSLog(@"%@",webData); 
    } 

Поместите эти 4 в виде контроллере

-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response 
    { 
     [webData setLength: 0]; 
    } 


// This method is responsible for storing the newly received data. The new data is appended to the NSMutableData object created in the button method, or the method that calls NSRUL methods. 
-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data 
{ 
    [webData appendData:data]; 
} 




//If an error is encountered during the download, the delegate receives a connection:didFailWithError: message. The NSError object passed as the parameter specifies the details of the error. It also provides the URL of the request that failed in the user info dictionary using the key NSURLErrorFailingURLStringErrorKey. 
-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error 
{ 
    // inform the user if connection fails// 
    NSLog(@"Connection failed! Error - %@ %@",[error localizedDescription],[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); 



} 




    //Finally, if the connection succeeds in downloading the request, the delegate receives the connectionDidFinishLoading: message 
    - (void)connectionDidFinishDownloading:(NSURLConnection*)connection destinationURL:(NSURL*)destinationURL { 

//[webView loadRequest:request];//if you wanted load the website into the webview 

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 


    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    [self saveFile:@"NSIcon" ofType:@"png" fromURL:@"http://website.com/NSIcon.png" inDirectory:documentsDirectory]; 



UIImage * newsstandImage = [self loadImage:@"NSIcon" ofType:@"png" inDirectory:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]]; 

    UIApplication *app = [UIApplication sharedApplication]; 
    [app setNewsstandIconImage:newsstandImage]; 

    NSLog(@"downloading..."); 

} 
+0

Спасибо, дорогой шариф, запрос должен быть URL-адресом? который является моим значком киоска? например: 'NSURLRequest * request = [NSURLRequest requestWithURL: [NSURL URLWithString: @" http://website.com/NSIcon.png "]];' –

+0

мой сбой из-за этого: '[webData setLength : 0]; ' –

+0

еще один вопрос должен ли я поместить этот код в' viewDidLoad'? 'NSURLConnection * conn ......' –

Смежные вопросы