zoukankan      html  css  js  c++  java
  • C#与Swift异步操作的差异

      作为一个从C#转到Swift的小菜鸡。。。最近做一个简单的请求API解析Json数据的小程序上碰到一堆小问题。尤其是在异步请求的时候,用惯了C#的async/await写法,在写Swift的时候也按着这个逻辑来做。结果发现回调函数没执行就直接返回了一个空数据出去导致程序一直崩溃(马丹啊)。查了老半天、问了一大堆人最后一个群友的一句话把我点醒了。。。。

      Swift的回调函数异步执行,它并没有C#的await来等待它执行完,它是直接往下执行程序的,这个时候你的回调函数并没有执行完。所以不能像C#那样用await等待异步操作把数据返回出来,然后对这个数据进行操作。而应该是把你对数据的处理方法用一个Closure传进异步方法里去。下面Po上我的错误代码和修改正确后的代码

    ✅正确代码:

    WeatherDataSource.GetWeather("北京") { (weatherdata) in
                NSLog(weatherdata.showapiResBody.cityInfo.c3 + "天气信息:" + weatherdata.showapiResBody.now.weather)
            }
    
    
     static func GetWeather(cityName:String,callback:(weatherdata:WeatherRootClass)->Void){
            let request = ShowApiRequest(url: "https://route.showapi.com/9-2", appId: AppInfo.appId, secret: AppInfo.secret)
            request.post(["area":"北京"],  callback: { (data) -> Void in
                let weatherinfo = WeatherRootClass(fromDictionary: data)
                NSLog(weatherinfo.showapiResBody.cityInfo.c3 + "天气信息:" + weatherinfo.showapiResBody.now.weather)
                callback(weatherdata: weatherinfo)
            })
        }

    ❌错误代码:

            var weatherinfo = WeatherRootClass()
            weatherinfo = WeatherDataSource.errorGetWeather("北京")
            NSLog(weatherinfo.showapiResBody.cityInfo.c3 + "天气信息:" + weatherinfo.showapiResBody.now.weather)
        
    
     static func errorGetWeather(cityName:String) -> WeatherRootClass{
            var result = WeatherRootClass()
            let request = ShowApiRequest(url: "https://route.showapi.com/9-2", appId: AppInfo.appId, secret: AppInfo.secret)
            request.post(["area":"北京"],  callback: { (data) -> Void in
                let weatherinfo = WeatherRootClass(fromDictionary: data)
                result = weatherinfo
            })
            return result
        }

    还有一个小问题是String转化为NSURL时String内包含有中文转换出来的NSURL就为nil

    对此的解决办法是:

    str = str.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!

    let nsurl =NSURL(string: str)!

    将String使用NSUTF8转码,然后使用转码后的String转化为NSURL

  • 相关阅读:
    Eclipse 重构功能的使用与重构快捷键
    Idea工具常用技巧总结
    Eclipse常用快捷键
    RabbitMQ的原理和使用
    总结消息队列RabbitMQ的基本用法
    rabbitmq常见运维命令和问题总结
    关于RabbitMQ关键性问题的总结
    Rabbit MQ 面试题相关
    RabbitMQ的使用总结
    史玉柱: 我的成功不是偶然(底下还有一堆相关链接)
  • 原文地址:https://www.cnblogs.com/Mr-Owl/p/5938574.html
Copyright © 2011-2022 走看看