Как мы можем сделать фоновую загрузку файлов в iphone? - PullRequest
2 голосов
/ 11 сентября 2009

как qik.com, ustream.com, я надеюсь узнать, как загрузить файл в фоновом режиме через iPhone SDK 3.0. Пожалуйста, дайте мне знать. Спасибо !

Ответы [ 5 ]

2 голосов
/ 12 сентября 2009

Непонятно, что вы подразумеваете под «в фоновом режиме», но если вы просто имеете в виду, что хотите загружать асинхронно, вы можете использовать NSURLConnection, NSURLRequest, или вы можете использовать эту превосходную библиотеку под названием ASIHTTPRequest . Он отлично работает и предоставляет простой способ показать прогресс загрузки и выгрузки.

0 голосов
/ 12 сентября 2009

См. этот пост за один (очень хорошо продуманный) ответ.

Хотя невозможно загрузить файлы в фоновом режиме, когда ваше приложение НЕ запущено, это вполне возможно сделать, когда ваше приложение работает. Таким образом, вы не влияете на поток переднего плана, а также можете увеличить его, чтобы показать прогресс и т. Д.

0 голосов
/ 11 сентября 2009

Вы можете сделать это таким образом (это в основном вырезка и вставка из одного из моих проектов) Автор сообщения упоминает некоторые посты на форумах разработчиков, но я не знаю, откуда они:

- (IBAction)startUpload:(id)sender {
    NSString *filename = [NSString stringWithFormat:@"iphone-%d.png", [NSDate timeIntervalSinceReferenceDate]];

    NSString *boundary = @"----BOUNDARY_IS_I";

    NSURL *url = [NSURL URLWithString:@"http://yourgreatwebsite.com/upload"];

    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];

    [req setHTTPMethod:@"POST"];

    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];

    [req setValue:contentType forHTTPHeaderField:@"Content-type"];

    NSData *imageData = UIImagePNGRepresentation([imageView image]);

    // adding the body
    NSMutableData *postBody = [NSMutableData data];


    // first parameter an image
    [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"filename\"; filename=\"%@\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:imageData];

    // second parameter information
    [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    //[postBody appendData:[@"Content-Disposition: form-data; name=\"some_other_name\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    //[postBody appendData:[@"some_other_value" dataUsingEncoding:NSUTF8StringEncoding]];
    //[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r \n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [req setHTTPBody:postBody];

    //start the spinner and deactivate the buttons...
    [self setButtonsEnabled:NO];


    [[NSURLConnection alloc] initWithRequest:req delegate:self];
  }

  #pragma mark urlconnection delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // this method is called when the server has determined that it
    // has enough information to create the NSURLResponse

    // it can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.
    // receivedData is declared as a method instance elsewhere
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // append the new data to the receivedData
    // receivedData is declared as a method instance elsewhere
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
    // release the connection, and the data object
    [connection release];

    // inform the user
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Upload Error" message:[NSString stringWithFormat:@"The upload failed with this error: %@", [error localizedDescription]] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];

    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data
    // receivedData is declared as a method instance elsewhere
#ifdef DEBUG
    NSLog(@"upload succeeded!");
#endif

    // release the connection, and the data object
    [connection release];

    NSString *response = [NSString stringWithCString:[receivedData bytes] length:[receivedData length]];    


#ifdef DEBUG
    NSLog(response);
#endif
}
0 голосов
/ 12 сентября 2009

Если вы используете фоновую загрузку, когда приложение не запущено, вы не можете (ОС не позволяет). Если фон работает во время работы приложения, ссылки и примеры кода, размещенные здесь, работают нормально.

0 голосов
/ 11 сентября 2009

Вы можете начать новый поток для загрузки вашего файла, посмотрите на класс NSThread, здесь есть ссылка http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSThread_Class/Reference/Reference.html ..., которая говорит, что вы также можете использовать asynchronousRequest из NSURLConnection, который запускает поток для вас, вот ссылка http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html

...