-1

これは明らかな回答の質問ですが、私は見つけられませんでした。AFNetworkingを使用するためのベストプラクティス

AFNetworkingを使用してRESTサーバーに接続しています。 画像のアップロードやダウンロード、jsonの投稿や取得などの基本的な作業をしています。

何かが変更されたときにUIを更新するのがベストプラクティスです。たとえば、プロファイル画像を正常にダウンロードして、テーブルビュー内で画像を変更する必要がある場合などです。

私はあなたがNSNotificationCenterを使用している現在、これを見ることができるように

APIConnector.h 

@interface APIConnector : NSObject 

-(void)downloadClientImageToSystem:(NSString *)imageURL; 

@end 

APIConnector.m 
-(void)downloadClientImageToSystem:(NSString *)imageURL{ 
    //setup 
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; 

    //Set url 
    NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",backendURL,imageURL]]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 

    //Create a download task 
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { 

     NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; 
     NSString *filename = [NSString stringWithFormat:@"%@.jpeg",[[imageURL componentsSeparatedByString:@"&imgIndex="] lastObject]]; 
     return [documentsDirectoryURL URLByAppendingPathComponent:filename]; 

    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) 
    { 
     if (error) { 
      NSLog(@"there was an error downloading profile image"); 
      [[NSNotificationCenter defaultCenter] postNotificationName:DLImageFail object:self]; 
     } 
     else{ 
      NSLog(@"File downloaded to: %@", filePath); 
      [[NSNotificationCenter defaultCenter] postNotificationName:DLImageSucces object:self]; 
     } 
    }]; 

    [downloadTask resume]; 
} 

私APIConnector AFNetworking使用していますが、これが最善の解決策である1級を持っていますか?私はデリゲートとブロックについて読んできました。私は私のテーブルビューを更新しようとするクラスのように、それを必要とするクラス内でAFNetworkingを実装する必要がありますか?

感謝:)

エキストラのコード例

-(void)executePostForURL:(NSString *)url dictionary:(NSDictionary *)dict success:(SuccessBlock)success failure:(FailureBlock)failure{ 
    [httpManager POST:url parameters:dict progress:nil 
       success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { 
        //somehow i need to return [responseObject valueForKey:@"updateLabelString"]; 
       } 
       failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { 

       }]; 
} 

私はのviewDidLoadでこれを呼び出すためにしようとしています。これはもちろん疑似コードであり、動作しません。どうすればlabelToUpdate.textに[responseObject valueForKey @ "updateLabelString"]値を解析できますか?

-(void)viewDidLoad{ 
    NSDictionary *dicToSendToServer; 
    UILabel *labelToUpdate = @"temp text"; 

    [apicon executePostForURL:@"serverurl" dictionary:dicToSendToServer success:^(NSString *test){ 
     labelToUpdate.text = test; 
    }failure:nil]; 
} 
+0

は個人的に、私はネットワーク要求をする私の方法に成功&失敗ブロックパラメータを追加し、私は一般的に次のように定義します。成功ブロックは通常、1つのparam(要求しているオブジェクト)であり、失敗ブロックはNSErrorオブジェクトを取ります。 – AdamPro13

+0

私は、成功と失敗のブロックパラメータを取るセクションを更新しました。 あなたが提案しているように、ソリューションはどのように見えますか? ({:; "image.png" @] 画像は= [UIImageがimagenamed})の障害 [APIのexecutePostForUrl: "URL" 辞書@:DIC大成功^だから私は同じように私のtableViewからこれを使用し理解する – 4FunAndProfit

答えて

4

私はこのように宣言します:

- (void)executePostForURL:(NSString *)url dictionary:(NSDictionary *)dict success:(void (^)(id objectYouRequested))success failure:(void (^)(NSError *error))failure; 

私もブロック構文の一部を回避するためにtypedefを使用したいです。

typedef void (^SuccessBlock)(id result); 
typedef void (^MySubclassedObjectSuccessBlock)(SubclassedObject *object); 
typedef void (^FailureBlock)(NSError *error); 

これは、その後に上記のメソッドの宣言を簡素化:

- (void)executePostForURL:(NSString *)url dictionary:(NSDictionary *)dict success:(SuccessBlock)success failure:(FailureBlock)failure; 
+0

:^({ [db savetolog:@ "could not executepost"]; })]; :) – 4FunAndProfit

+0

私はsuccesfull executePostForUrlを行ったときに、私はこのメソッドでこれを行うには、ユーザーインスタンスを返すしたいと思いますか? __block User * userを使用する。それからdispatch_async(成功したらget_main_queue?) – 4FunAndProfit

+0

あなたはそのようなことをすることができます。あなたのユーザーオブジェクトへの参照を取得してください。オブジェクトを成功ブロックに挿入する – AdamPro13

関連する問題