Receiving response using AFNetworking in Swift

痴心易碎 提交于 2019-12-11 12:05:49

问题


I am new to AFNetworking and I am trying to follow the tutorial of Raywenderlich on the same. So I have got this code for JSON parsing and I am struggling with converting that to Swift. I have tried many tutorials and StackOverflow answers but couldn't find a good explanatory one.

- (IBAction)jsonTapped:(id)sender
{
    // 1
    NSString *string = [NSString stringWithFormat:@"%@weather.php?format=json", BaseURLString];
    NSURL *url = [NSURL URLWithString:string];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    // 2
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        // 3
        self.weather = (NSDictionary *)responseObject;
        self.title = @"JSON Retrieved";
        [self.tableView reloadData];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        // 4
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
                                                            message:[error localizedDescription]
                                                           delegate:nil
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil];
        [alertView show];
    }];

    // 5
    [operation start];
}

So, can any one please help me regarding the basics of parsing data with AFNetworking?


回答1:


The problem is why you are going with Objc in Swift. There are many frameworks alternative to AFNetworking.

In fact, the same developer has developed the Network Library in Swift named Alamofire

You can use that framework and get the same response:

Here is the demo example of it!

func postWebserviceWithURL(strUrl: String, param: NSDictionary?, completionHandler: (NSDictionary?, NSError?) -> ()) -> (){

        Alamofire.request(.POST, strUrl, parameters: param as? [String : AnyObject], encoding: ParameterEncoding.URL).responseJSON { response in

            switch response.result {

            case .Success(let data):
                let json = data as? NSDictionary
                completionHandler(json, nil)
            case .Failure(let error):
                completionHandler(nil, error)
                self.showSingleAlert("app_name", message: error.localizedDescription)
            }
        }
    }



回答2:


Yes you can easily use AFnetworking library in swift fist of all you need to create Bridging-Header.h file and import AFNetworking.h into your Bridging-Header.h file

and Try this below code into your json method

let urlAsString = "<Your json URL in string>"   
        let manager = AFHTTPRequestOperationManager()
        manager.POST(
            urlAsString,
            parameters: <Parameter>,
            success: { (operation: AFHTTPRequestOperation!,
                responseObject: AnyObject!) in
print("JSON: " + responseObject.description)
},
failure: { (operation: AFHTTPRequestOperation!
    error: NSError!) in
  }
 )


来源:https://stackoverflow.com/questions/34669707/receiving-response-using-afnetworking-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!