I am trying to do a simple task of uploading an image to server from iOS app. However I am receiving the following error message after running it:
Error: Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
Any idea why? The following is my code for client side and server side respectively.
App side code:
-(void) uploadPhoto: (UIImage*) image{
NSString *urlString = @"myServerDNS.com/upload.php";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
NSDictionary *parameters = @{@"foo":@"bar"};
[manager POST:urlString
parameters:parameters
constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{[formData appendPartWithFormData:imageData name:@"file"];}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{NSLog(@"Success: %@", responseObject);}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{NSLog(@"Error: %@", error);}
];
}
Server side php code:
<?php
$foo = $_POST["foo"];
$target_dir = "Folder/" . basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir))
{
echo json_encode([
"Message" => "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.",
"Status" => "OK"
]);
} else {
echo json_encode([
"Message" => "Sorry, there was an error uploading your file.",
"Status" => "Error"
]);
}
?>