您好我是iOS的新手,需要将图像提交给php服务器。对于这个我 已将图像转换为base64格式。并需要发送此base64字符串 PHP服务器。 代码我正在使用这是,请帮助我在ios中全新
// Create your request string with parameter name as defined in PHP file
NSString *myRequestString = [NSString stringWithFormat:@"comment=%@",@"test data"];
// Create Data from request
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http://www.sdevices.ru/flashrecorder/speechtotext.php"]];
// set Request Type
[request setHTTPMethod:@"POST"];
// Set content-type
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
// Set Request Body
[request setHTTPBody:myRequestData];
// Now send a request and get Response
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
// Log Response
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
NSLog(@"%@",response); // here you get reasponse string
if ([response isEqualToString:@"Speech text!"]) {
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:@"Flash Recorder" message:@"Text is submitted!" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alrt show];
}
答案 0 :(得分:1)
我这篇帖子有基础64编码数据的答案
表示来自字符串
的NSDataNSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
和来自数据的NSString
NSString* str =[NSString stringWithUTF8String:[data bytes]];
直接来自我的代码的这个代码段很容易发布连接
-(BOOL) doPostConnection:(ServiceProps*) props delegate:(id<URLConnectionDelegate>) delegate
{
NSString *post = props.contentString;
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:props.connectionURL];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Data-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:delegate];
return conn != nil;
}
道具 - &gt;包装内容字符串和网址的基本类
@interface ServiceProps : NSObject
@property () NSString* contentString;
@property () NSURL* connectionURL;
@end
委托 - &gt;一个接口类,它包含你的post服务逻辑 内部取决于您的服务
@protocol URLConnectionDelegate <NSObject>
- (id) initWithConnectionDelegate:(id<ConnectionDelegate>)delegate;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data;
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
@end