Значок обновления газетного киоска - PullRequest
0 голосов
/ 02 апреля 2012

Я следую iOS 5 по учебнику [глава газетного киоска], но у меня проблема с обновлением иконки.

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

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

вот мой код, но ничего не происходит !! где я должен поставить эту строку кода? в моем приложении Delegate или 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)

1 Ответ

1 голос
/ 02 апреля 2012

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...");

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...