问题
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