标签: afnetworking-2

使用AFNetworking 2.0发布JSON数据

我有一个Web脚本,它通过HTTP POST请求接受JSON字符串作为输入.我遇到了几个相同的AFNetworking 1.x示例,有人可以指点我或给AFNetworking 2.0示例对带有格式化JSON作为输入的Web脚本执行HTTP POST请求吗?

谢谢

json http-post ios afnetworking-2

44
推荐指数
4
解决办法
5万
查看次数

AFNetworking 2:如何取消AFHTTPRequestOperationManager请求?

我将我的网络功能迁移AFNetworking到了AFNetworking v2,而不是AFHttpClientAFHTTPRequestOperationManager用来支持iOS6.

我的问题是,虽然AFHttpClient有使用.取消待处理请求的功能

- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method path:(NSString *)path;
Run Code Online (Sandbox Code Playgroud)

方法,在AFHTTPRequestOperationManager没有这种明显的方法.

我到目前为止所做的是AFHTTPRequestOperationManager继承和声明一个iVar

AFHTTPRequestOperation *_currentRequest;
Run Code Online (Sandbox Code Playgroud)

当我提出请求时,代码就是这样的

- (void)GetSomething:(NSInteger)ID success:(void (^)(MyResponse *))success failure:(void (^)(NSError *))failure
{
    _currentRequest = [self GET:@"api/something" parameters:@{@"ID": [NSNumber numberWithInteger:ID]} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        MyResponse *response = [MyResponse responseFromDictionary:responseObject];
        success(response);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        failure(error);

    }];
}
Run Code Online (Sandbox Code Playgroud)

我有一个

- (void)cancelCurrentRequest;
Run Code Online (Sandbox Code Playgroud)

所有这些的方法都是

- (void)cancelCurrentRequest
{
    if(_currentRequest) {
        [_currentRequest cancel]; _currentRequest = nil;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我不认为这是一个好的做法,当调用该方法时,我得到了 …

afnetworking-2

37
推荐指数
1
解决办法
2万
查看次数

使用AFNetworking 2.0上传图像

我用这个把头撞在墙上.我想UIImage从库中选择并将其上传到服务器,就像可以做到的那样<form action="http://blabla.request.cfm" method="post" enctype="multipart/form-data">.而不是成功我得到了这个错误:

error = Error Domain = NSCocoaErrorDomain Code = 3840"操作无法完成.(Cocoa error 3840.)"(JSON文本不是以数组或对象开头,而是选项允许未设置片段.)UserInfo = 0x145e5d90 {NSDebugDescription = JSON文本不以数组或对象和选项开头,以允许未设置片段.}

我试过这种方式:

-(void)uploadPhoto{
NSString *path = @"http://blabla.request.cfm";
NSData *imageData = UIImageJPEGRepresentation(self.imageView.image, 0.9);
int priv = self.isPrivate ? 1 : 0;
NSDictionary *parameters = @{@"username": self.username, @"password" : self.password, @"private" : @(priv), @"photo" : imageData};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:path parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    if(self.imageView.image){
        [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
    }
} success:^(AFHTTPRequestOperation *operation, id responseObject) …
Run Code Online (Sandbox Code Playgroud)

file-upload objective-c uiimageview ios afnetworking-2

33
推荐指数
1
解决办法
4万
查看次数

SSL固定和AFNetworking 2.5.0的问题(NSURLErrorDomain错误-1012.)

使用AFNetworking 2.5.0,我们一直很难通过SSL保护应用程序的网络连接.

我们使用自签名证书颁发机构,并使用固定证书实施自定义安全策略.

我们已经测试了AFNetworking提供的很多配置,但到目前为止还不幸运.我们收到的错误消息是:

2015-01-05 19:03:07.191 AppName [9301:319051]更新用户旅程时出错.错误:错误域= NSURLErrorDomain代码= -1012"操作无法完成.(NSURLErrorDomain错误-1012.)"UserInfo = 0x7ae056b0 {NSErrorFailingURLKey = https://api.XXX.com/XXX/XXX/,NSErrorFailingURLStringKey = https://api.XXX.com/XXX/XXX/ }

我们的证书适用于其他客户端,如cURL和Android.使用HTTP时,我们的实现也非常好.

是否有人知道与固定证书和AFNetworking相关的任何问题?如果是的话,我们非常感谢您提供的任何指示.

以下是实施的一部分:

+ (AFSecurityPolicy*)customSecurityPolicy {
   AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
   NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"der"];
   NSData *certData = [NSData dataWithContentsOfFile:cerPath];
   [securityPolicy setAllowInvalidCertificates:NO];
   [securityPolicy setValidatesCertificateChain:NO];
   [securityPolicy setPinnedCertificates:@[certData]];
   return securityPolicy;
}

+ (AFHTTPRequestOperationManager*)customHttpRequestOperationManager {
   AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
   manager.securityPolicy = [self customSecurityPolicy]; // SSL
   return manager;
}

+(void)getRequestWithUrl:(NSString*)url success:(void(^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void(^) (AFHTTPRequestOperation *operation, NSError *error))failure {
   [[UIApplication sharedApplication] …
Run Code Online (Sandbox Code Playgroud)

ssl ios afnetworking afnetworking-2

33
推荐指数
3
解决办法
2万
查看次数

AFNetworking 2.0 - "不可接受的内容类型:text/plain"

我正在使用AFNetworking 2.0从我正在构建的服务(localhost现在开始)中读取JSON .很正常的东西.

Node正在发送JSON,如下所示:

res.setHeader('Content-Type','application/json');
res.end( JSON.stringify(...));
Run Code Online (Sandbox Code Playgroud)

我的iOS首次传递代码试图像这样读取数据:

typedef void(^NextBlock)();
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:self.newestTimestampURL.absoluteString
    parameters:nil
    success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        //NSDictionary *response =
        NSLog(@"got %@", responseObject );
    }
    failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {
        NSLog(@"fail %@", error );
    }];
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

Error Domain=AFNetworkingErrorDomain Code=-1016 "Request failed: unacceptable content-type: text/plain" UserInfo=0xb783e30 {NSErrorFailingURLKey=http://localhost:3000/api/v1/log/newest, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0xb656a70> { URL: http://localhost:3000/api/v1/log/newest } { status code: 200, headers {
Connection = "keep-alive";
ContentType = "application/json";
Date = "Fri, 27 …
Run Code Online (Sandbox Code Playgroud)

json node.js ios ios7 afnetworking-2

28
推荐指数
3
解决办法
4万
查看次数

(可可错误3840.)"(字符0周围的值无效.)AFNetworking

使用GET方法从服务器检索文件时,我一直收到以下错误:

Error: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x16e81ed0 {NSDebugDescription=Invalid value around character 0.}
Run Code Online (Sandbox Code Playgroud)

我尝试了很多不同的东西,我相信它可能与我想要获得的文件上的JSON格式有关.

这是我一直在使用的代码:

_username = @"JonDoe";
NSDictionary *parameters = @{ @"username" : _username};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

[manager GET:@"http://.........."
  parameters:parameters
     success:^(AFHTTPRequestOperation *operation, id responseObject) {
         NSLog(@"JSON: %@", responseObject);
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"Error: %@", error);
     }];
Run Code Online (Sandbox Code Playgroud)

我的POST方法工作正常.我似乎无法用GET解决这个问题.有任何想法吗?谢谢.

cocoa-touch json objective-c ios afnetworking-2

28
推荐指数
1
解决办法
4万
查看次数

AFNetworking 2.0跟踪文件上传进度

我对AFNetworking 2.0比较陌生.使用下面的代码段,我已经能够成功将照片上传到我的网址.我想跟踪增量上传进度,但我找不到使用2.0版本执行此操作的示例.我的应用程序是iOS 7,所以我选择了AFHTTPSessionManager.

任何人都可以举例说明如何修改此代码段以跟踪上传进度吗?

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"myimage.jpg"], 1.0);

[manager POST:@"http://myurl.com" parameters:dataToPost constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileData:imageData name:@"attachment" fileName:@"myimage.jpg" mimeType:@"image/jpeg"];
} success:^(NSURLSessionDataTask *task, id responseObject) {
    NSLog(@"Success %@", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
    NSLog(@"Failure %@, %@", error, [task.response description]);
}];
Run Code Online (Sandbox Code Playgroud)

ios afnetworking-2

27
推荐指数
2
解决办法
2万
查看次数

如何在AFNetworking 2.0中设置请求超时和缓存策略?

我正在按照给定的示例代码

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];
Run Code Online (Sandbox Code Playgroud)

要更改超时和缓存策略,我'已经'破解了库并创建了

- (AFHTTPRequestOperation *)GET:(NSString *)URLString
                     parameters:(NSDictionary *)parameters
                          timeoutInterval:(NSTimeInterval)timeoutInterval
                    cachePolicy:(NSURLRequestCachePolicy)cachePolicy
                        success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"GET" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters];
    [request setTimeoutInterval:timeoutInterval];
    [request setCachePolicy:cachePolicy];
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
    [self.operationQueue addOperation:operation];

    return operation;
}
Run Code Online (Sandbox Code Playgroud)

这样做有干净的方法吗?

objective-c ios afnetworking afnetworking-2

26
推荐指数
2
解决办法
2万
查看次数

如何在AFNetworking 2.0中获得下载进度?

我正在使用AFURLSessionManager创建一个新的下载任务:

AFURLSessionManager* manager = ...

NSProgress* p = nil;
NSURLSessionDownloadTask* downloadTask =
        [manager downloadTaskWithRequest:request
                                 progress:&p
                              destination:^NSURL*(NSURL* targetPath, NSURLResponse* response) {...}
                        completionHandler:^(NSURLResponse* response, NSURL* filePath, NSError* error) {...}
        ];
[downloadTask resume];
Run Code Online (Sandbox Code Playgroud)

该文件下载得很好,但是,如何获得进度通知?

p总是设为零.我已经为此提出了一个问题.

我也试着打电话setDownloadTaskDidWriteDataBlock给经理,我确实收到了进度通知,但是我在文件下载后将它们全部收到组合.

似乎这个区域在AFNetworking 2.0中仍然有点儿麻烦

有任何想法吗?

objective-c ios afnetworking-2

25
推荐指数
2
解决办法
3万
查看次数

通缉:使用AFNetworking-2进行基本身份验证的JSON/POST的最新示例

我有一个玩具应用程序,使用基本身份验证安全性提交https JSON/POST.我被告知我应该考虑使用AFNetworking.我已经能够将AFNetwork-2安装到我的XCode项目(ios7目标,XCode5)中.但是这些例子似乎都与当前版本的AFNetworking-2无关,而是与之前的版本相关.AFNetworking文档相当稀疏,所以我正在努力将各个部分放在一起.非AFNetworking代码看起来像:

NSURL *url = [NSURL URLWithString:@"https://xxx.yyy.zzz.aaa:bbbbb/twig_monikers"];
NSMutableURLRequest *request = [NSMutableURLRequest
    requestWithURL:url
    cachePolicy: NSURLRequestUseProtocolCachePolicy
    timeoutInterval: 10.0];

NSData *requestData = [NSJSONSerialization dataWithJSONObject: [self jsonDict] options: 0 error: nil];
[request setHTTPMethod: @"POST"];
[request setValue: @"application/json" forHTTPHeaderField: @"Accept"];
[request setValue: @"application/json" forHTTPHeaderField: @"Content-Type"];
[request setValue:[NSString stringWithFormat: @"%d", [requestData length]] forHTTPHeaderField: @"Content-Length"];
NSData *plainPassText = [@"app_pseudouser:sample_password" dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64PassText = [plainPassText base64EncodedStringWithOptions: NSDataBase64Encoding76CharacterLineLength];
[request setValue:[NSString stringWithFormat: @"Basic %@", base64PassText] forHTTPHeaderField: @"Authorization"];

FailedCertificateDelegate *fcd=[[FailedCertificateDelegate alloc] init];
NSURLConnection *c=[[NSURLConnection alloc] initWithRequest:request delegate:fcd startImmediately:NO];
[c setDelegateQueue:[[NSOperationQueue alloc] …
Run Code Online (Sandbox Code Playgroud)

json objective-c ios afnetworking afnetworking-2

25
推荐指数
1
解决办法
1万
查看次数