因爲我將圖像轉換爲base64字符串,並上傳它塞雷爾語用NSURLSessionsDataTask
的示例 -如何通過NSUrlSession IOS發送的base64字符串
NSString *encodedString = [[self encodeToBase64String:imgParcel]stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
[self.package.arrParcelImages addObject:encodedString]
並把它發送這樣的...
NSDictionary *postParameters = @{@"userID":@"1",@"images":self.package.arrParcelImages}
NSData *postData = [NSJSONSerialization dataWithJSONObject:postParameters options:NSJSONWritingPrettyPrinted error:&error];
NSString *dataString = = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"image/png" forHTTPHeaderField:@"Content-Type"];
NSString *strValue = [NSString stringWithFormat:@"%@",[USER_DEFAULTS objectForKey:UD_X_API_VALUE]];
if (strValue != nil) {
[request addValue:strValue forHTTPHeaderField:[USER_DEFAULTS objectForKey:UD_X_API_KEY]];
}
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *taskData, NSURLResponse *taskResponse, NSError *taskError) {
//NSLog(@"Start - Response:%@ %@\n", taskResponse, taskError);
dispatch_async(dispatch_get_main_queue(), ^{
if (taskError) {
NSLog(@" Error = %@",[taskError localizedDescription]);
completionBlock(nil,taskError,task);
}
else {
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:taskData options:kNilOptions error:&error];
if (json) {
NSLog(@" JSON = %@",json);
}
else {
NSString* newStr = [[NSString alloc] initWithData:taskData encoding:NSUTF8StringEncoding];
NSLog(@"Error: %@",newStr);
}
completionBlock(json,nil,task);
}
});
}];
[postDataTask resume];
但這不是上傳base64字符串到服務器我在做什麼錯請幫忙
順便說一句,'NSData * postData = postData = [NSJSONSerialization ...];'是不對的。擺脫額外的'postData'。同樣,'NSString * postString = = ...'是不正確的。你有一個額外的'='在那裏... – Rob
我在這裏輸入了這就是爲什麼它看起來像這樣,但在代碼中它是完美的 –