我刚刚开始使用AFNetworking,但我似乎无法弄清楚如何让以下工作.
我的URL指向一个PHP文件,该文件将从数据库中检索的数据打印为JSON,但是使用AFNetworking我收到"预期内容类型"错误.
我的代码如下,但使用不同的URL.
NSURL *url = [NSURL URLWithString:@"http://www.example.com/json.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id json) {
NSLog(@"JSON: %@", [json valueForKeyPath:@"results"]);
} failure:nil];
[operation start];
Run Code Online (Sandbox Code Playgroud) 我正在开发iOS应用程序,并且在使用AFNetworking发出http请求时遇到了一些麻烦.
当我运行代码时,我收到错误:EXC_BAD_ACCESS(code = 2 address = 0x0).我尝试setCompletionBlock时发生错误.
我是Objective-C的新手,这让我很难过.
先感谢您.感谢大家的帮助!
#import "AFNetworking.h"
#import <Cordova/CDV.h>
#import "UploadImg.h"
@implementation UploadImg
- (void) uploadImg:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options{
NSURL *url = [NSURL URLWithString:@"http://test.com/mobile/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = [NSData dataFromBase64String:[arguments objectAtIndex:1]];
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
[params setObject:@"TEST_STYLE" forKey:@"styleType"];
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload.php" parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:imageData name:@"imageName" fileName:@"image.png" mimeType:@"image/png"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"success");
}
failure:^(AFHTTPRequestOperation *operation, NSError …Run Code Online (Sandbox Code Playgroud) 以下代码块用于将图像文件提交到数据库.它已停止工作:即使打印SUCCESS,服务器上也看不到任何图像.关于如何调试这个的任何建议?
EDITS
我在调试器中打印了imageData并得到了一个内存地址数组,所以我几乎可以肯定我有一个图像.
- (void)postActivityImage:(Spot*)localSpot
{
NSLog(@"%s",__func__);
NSString *url = [NSString stringWithFormat:@"v1/activity/%@/image", localSpot.uniqueID];
UIImage *image = [UIImage imageWithContentsOfFile:localSpot.imageLocalURL];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5f);
NSURLRequest *request = [httpClient_ multipartFormRequestWithMethod:@"POST"
path:url
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData
name:@"test"
fileName:@"test"
mimeType:@"image/jpeg"];
}];
AFJSONRequestOperation *ro;
ro = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSURLResponse *response, id JSON) {
NSLog(@"success: %@", JSON);
NSLog(@"SUCCESS - IMAGE POSTED.");
[self updateSpotSubmitInProgressStatusWithActivityFinished:ImagePost andSuccess:YES];
[[NSNotificationCenter defaultCenter] postNotificationName:SUBMIT_STATUS object:self userInfo:nil];
self.spot.imageSubmitted = YES;
} failure:^(NSURLRequest *request, NSURLResponse *response, NSError *error, id …Run Code Online (Sandbox Code Playgroud) 我想使用AFNetwork下载多个文件,但我不知道如何实现这个?如您所见,我创建了一个操作数组并在其中添加了3个任务
NSMutableArray *operations = [NSMutableArray array];
NSArray *requestArray = @[ @"...task1.zip", @"task2.zip", @"task3.zip" ];
for (int i = 0; i < 3; i++) {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[requestArray objectAtIndex:i]]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:[[requestArray objectAtIndex:i] lastPathComponent]];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Successfully downloaded file to %@", path);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
[operation setDownloadProgressBlock:^(NSUInteger …Run Code Online (Sandbox Code Playgroud) 我正在使用AFNetworking方法将我的图像加载到UIBUttons中.我的目标是在加载后用淡入淡出的动画显示图像.
[leftBtn setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:leftImageUrl]] placeholderImage:nil forState:UIControlStateNormal success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
[UIView animateWithDuration:0.4 animations:^() {leftBtn.alpha = 1;}completion:^(BOOL finished){}];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
//
}];
Capturing 'leftBtn' strongly in this block is likely to lead to a retain cycle
Run Code Online (Sandbox Code Playgroud)
我理解为什么我得到上述警告并寻找一种聪明的方法来解决它.谢谢
这是崩溃报告不确定原因.我使用AFHTTPRequestOperation setCompletionBlockWithSuccess:failure:进行调用.在完成块中,我得到结果并将其传递给我的数据模型上的类别类,以插入到核心数据表中.
下面是崩溃日志..
最后的例外回溯:
0 CoreFoundation 0x2fed7f4e __exceptionPreprocess + 126
1 libobjc.A.dylib 0x3a2b06aa objc_exception_throw + 34
2 CoreFoundation 0x2fedb8e2 -[NSObject(NSObject) doesNotRecognizeSelector:] + 198
3 CoreFoundation 0x2feda1ce ___forwarding___ + 702
4 CoreFoundation 0x2fe29594 __forwarding_prep_0___ + 20
5 <myappname> 0x000bbfe8 +[BTRooms(Data) createNewRoom:withNode:] (BTRooms+Data.m:32)
6 <myappname> 0x000b034e __28-[BTNet createRoom:friends:]_block_invoke (BTNet.m:551)
7 <myappname> 0x0008fd10 __64-[AFHTTPRequestOperation setCompletionBlockWithSuccess:failure:]_block_invoke139 (AFHTTPRequestOperation.m:279)
8 libdispatch.dylib 0x3a793d76 _dispatch_call_block_and_release + 6
9 libdispatch.dylib 0x3a793d62 _dispatch_client_callout + 18
10 libdispatch.dylib 0x3a79a7bc _dispatch_main_queue_callback_4CF$VARIANT$mp + 264
11 CoreFoundation 0x2fea281c __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 4
12 CoreFoundation 0x2fea10f0 …Run Code Online (Sandbox Code Playgroud) 如何使用AFHttpClient设置时间间隔
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@""]];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
Run Code Online (Sandbox Code Playgroud) 我正在将我的项目迁移到AFNetworking 2.0.使用AFNetworking 1.0时,我编写了代码来记录控制台中的每个请求/响应.这是代码:
-(AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request
success:(void (^)(AFHTTPRequestOperation *, id))success
failure:(void (^)(AFHTTPRequestOperation *, NSError *))failure
{
AFHTTPRequestOperation *operation =
[super HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject){
[self logOperation:operation];
success(operation, responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error){
failure(operation, error);
}];
return operation;
}
-(void)logOperation:(AFHTTPRequestOperation *)operation {
NSLog(@"Request URL-> %@\n\nRequest Body-> %@\n\nResponse [%d]\n%@\n%@\n\n\n",
operation.request.URL.absoluteString,
[[NSString alloc] initWithData:operation.request.HTTPBody encoding:NSUTF8StringEncoding],
operation.response.statusCode, operation.response.allHeaderFields, operation.responseString);
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用AFNetworking 2.0做同样的事情,根据我的理解,这意味着使用NSURLSessionDataTask对象代替AFHTTPRequestOperation.这是我的镜头.
-(NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLResponse *, id, NSError *))completionHandler {
NSURLSessionDataTask *task = [super dataTaskWithRequest:request completionHandler:^(NSURLResponse …Run Code Online (Sandbox Code Playgroud) 我正在开发一个基于iOS5的项目.我想通过cocoapods使用AFNetworking 2.0.但是需要'iOS6 +'.我可以在iOS5上使用AFNetworking 1.x而在iOS6 +上使用2.0吗?
谢谢
我试图发布到支持TLS 1.2的服务器 - 至少当我在浏览器中执行GET时,我可以验证通信是否使用TLS 1.2并且证书由证书颁发机构验证.但是,当我尝试使用AFNetworking iOS 9.0(13A4305g)/ Xcode 7-beta4将我的代码POST到该服务器时,我得到握手失败.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializerWithContentType:@"application/x-www-form-urlencoded"];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:requestString parameters:@{ @"apiKey" : MY_API_KEY,
@"payload" : [MyParams paramsForPOSTAsJSON] }
success:^(AFHTTPRequestOperation *operation, NSDictionary *responseDict) {
...
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
myLog(@"Communication failed: %@", error);
}];
Run Code Online (Sandbox Code Playgroud)
失败:
2015-08-06 15:01:08.398 MyApp[1795:394055] CFNetwork SSLHandshake failed (-9824)
2015-08-06 15:01:08.409 MyApp[1795:394055] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9824)
2015-08-06 15:01:08.412 MyApp[1795:393999] MyClass sendDataToServer Communication failed: Error Domain=NSURLErrorDomain Code=-1200 "An SSL error …Run Code Online (Sandbox Code Playgroud) afnetworking ×10
ios ×9
objective-c ×5
ios5 ×2
iphone ×2
content-type ×1
http ×1
ios9 ×1
json ×1
ssl ×1
xcode ×1