将json调用语法从Objective-C转换为Swift的正确方法是啥?

Posted

技术标签:

【中文标题】将json调用语法从Objective-C转换为Swift的正确方法是啥?【英文标题】:What is the right way to convert json call syntax from Objective-C to Swift?将json调用语法从Objective-C转换为Swift的正确方法是什么? 【发布时间】:2015-11-02 04:04:03 【问题描述】:

我正在将 ViewController 从 Objective-C 更新到 Swift,并遇到了几个错误,我的原始代码是:

/*        Line 161 read: NSString *dateString = [NSString stringWithFormat:@"%i-%i", start.month, start.day];
*/       This is from Objective-c file to call Holiday.json file 


NSString *dateString = [NSString, stringWithFormat;@"%li-%li", (long)start.month, (long)start.day];

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Holidays" ofType:@"json"];

NSString *holidayJSON = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];

if (holidayJSON) 

    NSData *jsonData = [holidayJSON dataUsingEncoding:NSUTF8StringEncoding];



    NSDictionary *results = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];

    NSDictionary *holiday = [results objectForKey:dateString];

    NSDictionary *titleDescription = [holiday objectForKey:@"holidays"];

    NSLog(@"holiday %@", titleDescription);



    NSString *title = [[titleDescription valueForKey:@"title"]objectAtIndex:0];

    NSString *description = [[titleDescription valueForKey:@"description"]objectAtIndex:0];



    NSLog(@"title: %@, description: %@", title, description);

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:description delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];

    [alertView show];





NSLog( @"Selected %ld/%ld - %ld/%ld", (long)range.startDay.day, (long)range.startDay.month, (long)range.endDay.day, (long)range.endDay.month);



else 

    NSLog( @"No selection" );

  


在尝试将其更改为 Swift 时,我遇到了几个错误:

// have calendar present a holiday from the JSON file for each day


let filePath: String = NSBundle.mainBundle().pathForResource("Holiday", ofType: "json") as String!
let jsonData = NSData(contentsOfFile:filePath) as NSData!
let dateString = ["%li-%li",DayView.monthstart.day] as NSString!
var holidayJSON: String = NSString(contentsOfFile: filePath, encoding: NSUTF8StringEncoding, error: nil)
if holidayJSON 
    var jsonData: NSData = holidayJSON.dataUsingEncoding(NSUTF8StringEncoding)
    var results: [NSObject : AnyObject] = NSJSONSerialization.JSONObjectWithData(jsonData, options: 0, error: nil)
    var holiday: [NSObject : AnyObject] = results[dateString]
    var titleDescription: [NSObject : AnyObject] = holiday["holidays"]
    NSLog("holiday %@", titleDescription)
    var title: String = titleDescription.valueForKey("title").objectAtIndex(0)
    var description: String = titleDescription.valueForKey("description").objectAtIndex(0)
    NSLog("title: %@, description: %@", title, description)
    var alertView: UIAlertView = UIAlertView(title: title, message: description, delegate: nil, cancelButtonTitle: "Ok", otherButtonTitles: nilnil)
    alertView.show()

NSLog("Selected %ld/%ld - %ld/%ld", range.startDay.day, range.startDay.month, range.endDay.day, range.endDay.month)

【问题讨论】:

您遇到了哪些错误以及发生在哪些行上? 我建议你不要转换语法。使用 Swift 特性进行编码。例如,对于 JSON 解析,您可以尝试 SwiftyJSon。 谢谢,我现在主要转换了大部分。我只收到警告“UIAlertView 在 ios9 中已弃用:UIAletView 已弃用”但它仍然无法正常工作,因为我需要找到正确的函数来调用日期。 【参考方案1】:

我对coding/***/etc..etc还是很陌生...所以当我提出这个问题时,我正在寻找关于如何解决问题的其他想法,我遇到了一个视频说我可以使用桥接在 swift 项目中使用 Objective-c 的头文件。这是我当时没有想到的一种解决方案。但我能够从更有经验的人那里获得一些帮助,这是一个不会出现错误的 swift 版本:

`//        Line 161 read: NSString *dateString = [NSString                           stringWithFormat:@"%i-%i", start.month, start.day];
//        This is from Objective-c file to call Holiday.json file

func holidayForDate(date:CVDate) 
//let cal = NSCalendar.currentCalendar()
// let components = cal.components([.Month, .Day], fromDate: date)
let dateString = "\(date.month)-\(date.day)"

guard let path : String = NSBundle.mainBundle().pathForResource("Holiday", ofType: "json") else 
    // TODO error handling?
    return

guard let jsonData = NSData(contentsOfFile: path) else 
    // TODO error handling?
    return

do 
    guard let dict:[String:AnyObject] = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as? [String : AnyObject] else 
        // TODO error handling
        return
    
    let holidays:[[String:String]] = dict[dateString] as! [[String:String]]
    if let holiday = holidays.first 
        let title = holiday["title"]
        let description = holiday["description"]
        UIAlertView(title: title, message: description, delegate: nil, cancelButtonTitle: "OK").show()
    

catch 
    NSLog("\(error)")

`

【讨论】:

以上是关于将json调用语法从Objective-C转换为Swift的正确方法是啥?的主要内容,如果未能解决你的问题,请参考以下文章

Objective-C:如何将以下 JSON 转换为可用数据

将 NSStrings 转换为 C 字符并从 Objective-C 调用 C 函数

将objective-c typedef转换为其等效的字符串

将objective-c块转换为Swift闭包

如何将 Objective-C 的完成块转换为 Swift?

将 Objective-C 中的函数转换为 swift