2015-02-17 2 views
2

У меня есть этот код, ниже которого посылает изображение и текст на моем сервере:NSURLSessionUploadTask не загружать изображения с параметрами

NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration]; 

    self.session = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate:self delegateQueue: nil]; 

    NSString *requestURL = @"http://www.website.com.br/receive.php?name=StackOverflow"; 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestURL]]; 

    [request setHTTPMethod:@"POST"]; 

    UIImage *imagem = [UIImage imageNamed:@"Image.jpg"]; 

    NSData *imageData = UIImageJPEGRepresentation(imagem, 1.0); 

    self.uploadTask = [self.session uploadTaskWithRequest:request fromData:imageData]; 

    [self.uploadTask resume]; 


-(void)URLSession:(NSURLSession *)session 
     dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{ 

    NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
    NSLog(@"%@",newStr); 
} 

PHP

<?php 
echo $_POST['name']; 
?> 

Проблема с этим кодом является что метод didReceiveData не получает данные, поступающие на сервер, он получает только NSData, когда я помещаю этот код в файл php:

print_r($_FILES); 

И все же он возвращает пустой массив, почему это происходит?

решаемые

Ну, я решил мою проблему, отпускает, в .h файле необходимо реализовать эти протоколы и одно свойство:

< NSURLSessionDelegate, NSURLSessionTaskDelegate> 
@property (nonatomic) NSURLSessionUploadTask *uploadTask; 

, тогда как в .m файл существует метод типа IBAction и что это связано с определенной кнопки существующие в нашей точки зрения, нам нужно только сделать это:

- (IBAction)start:(id)sender { 

    if (self.uploadTask) { 
     NSLog(@"Wait for this process finish!"); 
     return; 
    } 

    NSString *imagepath = [[self applicationDocumentsDirectory].path stringByAppendingPathComponent:@"myImage.jpg"]; 
    NSURL *outputFileURL = [NSURL fileURLWithPath:imagepath]; 


    // Define the Paths 
    NSURL *icyURL = [NSURL URLWithString:@"http://www.website.com/upload.php"]; 

    // Create the Request 
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:icyURL]; 
    [request setHTTPMethod:@"POST"]; 

    // Configure the NSURL Session 
    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.sometihng.upload"]; 

    NSURLSession *upLoadSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil]; 

    // Define the Upload task 
    self.uploadTask = [upLoadSession uploadTaskWithRequest:request fromFile:outputFileURL]; 

    // Run it! 
    [self.uploadTask resume]; 

} 

и реализовать некоторые делегирует методы:

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend { 

    NSLog(@"didSendBodyData: %lld, totalBytesSent: %lld, totalBytesExpectedToSend: %lld", bytesSent, totalBytesSent, totalBytesExpectedToSend); 

} 

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { 
    if (error == nil) { 
     NSLog(@"Task: %@ upload complete", task); 
    } else { 
     NSLog(@"Task: %@ upload with error: %@", task, [error localizedDescription]); 
    } 
} 

И для отделки, вам нужно создать PHP файл с этим кодом:

<?php 

$fp = fopen("myImage.jpg", "a");//If image come is .png put myImage.png, is the file come is .mp4 put myImage.mp4, if .pdf myImage.pdf, if .json myImage.json ... 

$run = fwrite($fp, file_get_contents("php://input")); 

fclose($fp); 

?> 

ответ

0

Вы должны преобразовать NSData в более управляемым формате, как в NSArray. Для этого вы должны попробовать что-то вроде:

NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data] 
+0

У меня есть два NSDatas внутри моего кода, один для отправки данных и другие, чтобы получить, как я поместил ваш код в обоих? – LettersBa

+0

Я использовал в методе didReceiveData: чтобы разблокировать данные, и я получаю сообщение об ошибке: непонятный архив (0x41, 0x72, 0x72, 0x61, 0x79, 0xa, 0x28, 0xa) ' – LettersBa

+0

Я разрешил свою проблему, спасибо ... – LettersBa

2

Пример кода для загрузки изображения в Dropbox.

// 1. config 
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; 

// 2. if necessary set your Authorization HTTP (example api) 
// [config setHTTPAdditionalHeaders:@{@"<setYourKey>":<value>}]; 

// 3. Finally, you create the NSURLSession using the above configuration. 
NSURLSession *session = [NSURLSession sessionWithConfiguration:config]; 

// 4. Set your Request URL (example using dropbox api) 
NSURL *url = [Dropbox uploadURLForPath:<yourFullPath>];; 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; 

// 5. Set your HTTPMethod POST or PUT 
[request setHTTPMethod:@"PUT"]; 

// 6. Encapsulate your file (supposse an image) 
UIImage *image = [UIImage imageNamed:@"imageName"]; 
NSData *imageData = UIImageJPEGRepresentation(image, 1.0); 

// 7. You could try use uploadTaskWithRequest fromData 
NSURLSessionUploadTask *taskUpload = [session uploadTaskWithRequest:request fromData:imageData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 

    NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response; 
    if (!error && httpResp.statusCode == 200) { 

     // Uploaded 

    } else { 

     // alert for error saving/updating note 
     NSLog(@"ERROR: %@ AND HTTPREST ERROR : %ld", error, (long)httpResp.statusCode); 
     } 
}]; 

- (NSURL*)uploadURLForPath:(NSString*)path 
{ 
    NSString *urlWithParams = [NSString stringWithFormat:@"https://api-content.dropbox.com/1/files_put/sandbox/%@/%@", 
           appFolder, 
           [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];  
    NSURL *url = [NSURL URLWithString:urlWithParams]; 
    return url; 
} 
+0

Как мы можем передавать параметры с файлом? – gypsicoder

+0

@gypsicoder вы можете использовать '[config setHTTPAdditionalHeaders: @ {@" Authorization ": [Dropbox apiAuthorizationHeader]}];' например, чтобы добавить авторизацию Dropbox в заголовок - подробнее см. Здесь [link] (https: // www. dropbox.com/developers-v1/core/docs#oa2-authorize) - api –

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