Search code examples
iosiphonejsonswiftafnetworking-2

Receiving response using AFNetworking in Swift


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?


Solution

  • 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)
                }
            }
        }