Objective-C 如何使用 AFNetwork 上传字符串

Posted

技术标签:

【中文标题】Objective-C 如何使用 AFNetwork 上传字符串【英文标题】:Objective-C How to upload String with using AFNetwork 【发布时间】:2015-09-03 03:27:52 【问题描述】:

我使用 AFNetwork 将照片和字符串(我将 uitextview 转换为字符串)上传到我的服务器并保存在数据库中,但我不知道使用 AFNetwork 上传字符串,但我使用它来上传我的照片,它可以工作这是我的用于 viewcontroller 的 php 代码

<?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);
     ];

【问题讨论】:

你应该修正引号 【参考方案1】:

使用 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];

【讨论】:

我忘记了,我要上传的字符串是NSString *comment = _commentText.text;【参考方案2】:

您可以使用以下代码上传评论字符串..

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];

它不会出现作为可接受的内容类型是 NSSet。你只传递了 NSSet……!检查一下。

希望对你有帮助......!

【讨论】:

谢谢,但在manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json",@"text/html",nil]; 中有错误是方法调用的参数太多,预期为 1,有 3 个

以上是关于Objective-C 如何使用 AFNetwork 上传字符串的主要内容,如果未能解决你的问题,请参考以下文章

如何在c++中,调用objective-c

Objective-C 观察者 - 如何在 Swift 中使用

Objective-c:如何使用自动布局向 UIView 添加边框 [关闭]

如何在 Swift 中使用 Objective-C #define

如何在objective-c中使用didSelectRowAtIndexPath

如何使用 Swift 从 Objective-C 启动实例类型