将文件发送到服务器并接收反馈

时间:2014-08-17 20:08:55

标签: objective-c

我有这个代码将文件发送到我的服务器:

  NSData *data = [NSData dataWithContentsOfFile:path];
    NSMutableString *urlString = [[NSMutableString alloc] initWithFormat:@"name=thefile&&filename=recording"];
    [urlString appendFormat:@"%@", data];
    NSData *postData = [urlString dataUsingEncoding:NSASCIIStringEncoding
                               allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    NSString *baseurl = @"http://websitetester.com/here.php";

    NSURL *url = [NSURL URLWithString:baseurl];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    [urlRequest setHTTPMethod: @"POST"];
    [urlRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [urlRequest setValue:@"application/x-www-form-urlencoded"
      forHTTPHeaderField:@"Content-Type"];
    [urlRequest setHTTPBody:postData];

    NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
    [connection start];

    NSLog(@"File Send to server!");

这段代码完美无缺,但我希望收到服务器的回复,我在代码末尾显示的php文件:

<?php

if(...){

...

echo "Data Received";

}else{

...

echo "Error in server";
}

?>

所有我正在尝试的是在php中收到这个回声并在我的应用程序中显示警报,我可以在我的代码中实现代码来执行此操作吗?

EDIT 

嘿,我找到了一个在objetive-c中收到返回数据的代码,代码是:

NSURLResponse* response;
    NSError* error;


    NSData* result = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];

    NSString *returnString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
    NSLog(@"return: %@",returnString);

现在代码按我预期的方式工作。

0 个答案:

没有答案
相关问题