Objective-C Как загрузить строку с помощью AFNetwork

Я использую AFNetwork для загрузки фотографии и строки (я конвертирую uitextview в строку) на свой сервер и сохраняю в базе данных, но я не знаю, использовать AFNetwork для загрузки строки, но я использую ее для загрузки своей фотографии, это работает, это мой php код использовать с viewcontroller

<?php
include(“connect.php");
$uploaddir = "post_comment/original/";      //Uploading to same directory as PHP file
$file = basename($_FILES['userfile']['name']);
$uploadFile = $file;
$randomNumber = rand(0, 99999);
$newName = $uploaddir . $randomNumber . $uploadFile;
$comment_text = nl2br($_POST['comment']);
$post_no = $_POST['post_no'];
$mem_slug = $_POST['id'];
$timest = date("Y-m-d H:i:s");
echo  "it is: ".$file;


if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
echo "Temp file uploaded. \r\n";
} else {
echo "Temp file not uploaded. \r\n";
}

if ($_FILES['userfile']['size']> 3000000) {
exit("Your file is too large.");
}


if(copy($_FILES['userfile']['tmp_name'],$newName)){
$sql3 = $conn->prepare("INSERT INTO `post_comment`(`comment_id`,`post_id`,`member_id`,`comment`,`image`,`status`,`timestp`) VALUES('',:postid,:member,:comment,:image,'1',:timestp)");
$sql3 ->bindValue(':postid',$post_no);
$sql3 ->bindValue(':member',$mem_slug);
$sql3 ->bindValue(':comment',$comment_text);
$sql3 ->bindValue(':image',$newName);
$sql3 ->bindValue(':timestp',$timest);
$sql3 ->execute();
}
echo "upload finished";
?>

Viewcontroller.m

NSString *comment = _commentText.text;
NSDictionary *data= @{@"post_id":urlpost,@"member_id":member_id,@"comment":self.commentText.text};
[manager POST:@"http://www.mysiteurl.com/member/comment_upload2.php"parameters:data constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
[formData appendPartWithFileData:UIImageJPEGRepresentation(self.image, 100) name:@"userfile" fileName:@"img.jpg" mimeType:@"image/jpg"];
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSString* str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"response is :  %@",str);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(@"Error: %@ *****", error);
}];
}

0

Решение

Используйте AFNetwork для загрузки изображения и строки.

попробуй этот код

AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://www.mysiteurl.com"]];
NSData *imageData = UIImageJPEGRepresentation(yourimage.image, 0.5);
NSDictionary *parameters= @{@"post_id":urlpost,@"member_id":member_id,@"comment":self.commentText.text};
AFHTTPRequestOperation *op = [manager POST:@"/member/comment_upload2.php" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//do not put image inside parameters dictionary as I did, but append it!
[formData appendPartWithFileData:imageData name:@"file" fileName:[NSString stringWithFormat:@"photo_%f.jpg",[NSDate timeIntervalSinceReferenceDate]] mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);

[[NSNotificationCenter defaultCenter] postNotificationName:@"PostAdded" object:nil];
[self.navigationController popViewControllerAnimated:YES];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@ ***** %@", operation.responseString, error);
}];
[op start];
0

Другие решения

Вы можете использовать код ниже, чтобы загрузить строку комментария.

NSString *comment = _commentText.text;
NSDictionary *data= @{@"post_id":urlpost,@"member_id":member_id,@"comment":self.commentText.text};

NSString *urlString=@"http://www.mysiteurl.com/member/comment_upload2.php”;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json",@"text/html", nil];
manager.requestSerializer=[AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
//manager.responseSerializer=[AFJSONResponseSerializer serializer];
NSString *stringCleanPath = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[manager POST:stringCleanPath parameters:maindict success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *jsondict =responseObject;
NSLog(@"jsondict>>>%@",jsondict);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error is %@",error);
[delegate failedResponseWithAnyType:[error localizedDescription] withServiceType:serviceTypeString];
}];

// Или вы можете попробовать загрузить как строку, так и фотографию, используя приведенный ниже код

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json",@"text/html", nil];
manager.requestSerializer=[AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
//manager.responseSerializer=[AFJSONResponseSerializer serializer];
NSString *stringCleanPath = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *comment = _commentText.text;
NSDictionary *data= @{@"post_id":urlpost,@"member_id":member_id,@"comment":self.commentText.text};
[manager POST:stringCleanPath
parameters:data constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
[formData appendPartWithFileData:UIImageJPEGRepresentation(self.image, 100) name:@"userfile" fileName:@"img.jpg" mimeType:@"image/jpg"];
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSString* str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"response is :  %@",str);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(@"Error: %@ *****", error);
}];
}

Проверьте на AFURLResponseSerialization.m

- (instancetype)init метод

self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];

Это не придет, так как acceptContentTypes является NSSet. Вы передаете NSSet только …! Проверьте это.

Надеюсь, это поможет вам …….!

0

По вопросам рекламы [email protected]