我創建包含數組和字符串和其他客戶端信息一個NSDictionary,使用的setObject forKey。當我NSLog數據時,一切看起來都很棒,格式就是它應該的樣子。我也已將NSDictionary轉換爲NSData:AFNetworking,上傳簡單的NSData與POST
NSData *userData = [NSJSONSerialization dataWithJSONObject:userDict options:NSJSONWritingPrettyPrinted error:&error];
我需要知道的是如何使用POST將它上載到服務器。我找到了以下代碼片段來上傳照片。我的問題是我可以簡單地使用我的NSDictionary作爲參數(請求中的參數),它有點大。如果不是,我該如何發送我的NSData對象userData?我非常喜歡AFNetworking,並專門用於我所有的下載需求。這是我第一次上傳對象。 感謝
NSData *imageData = UIImagePNGRepresentation(pageImage);
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://www.SERVER.com"]];
//You can add POST parameteres here
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
author, @"author",
title, @"title",
nil];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:@"/PATH/TO/WEBSERVICE.php" parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
//This is the image
[formData appendPartWithFileData: imageData name:@"cover_image" fileName:@"temp.png" mimeType:@"image/png"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//Setup Upload block to return progress of file upload
[operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
float progress = totalBytesWritten/(float)totalBytesExpectedToWrite;
NSLog(@"Upload Percentage: %f %%", progress*100);
}];
//Setup Completeion block to return successful or failure
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *response = [operation responseString];
NSLog(@"response: [%@]",response);
//Code to run after webservice returns success response code
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error: %@", [operation error]);
//Code to Run if Failed
}];
[operation start];
謝謝!需要修復服務器上的一些錯誤,但它在我的終端上像一個魅力。愛AFNetworking !!! – LittlePeculiar