如何在swift中使用dispatch_async

时间:2015-02-18 11:32:44

标签: swift

func get_data_from_server() {
    let urlPath = NSString(format:"url")
    var url: NSURL = NSURL(string: urlPath)!
    let data : NSData = NSData(contentsOfURL: url)!
    var error: NSErrorPointer = nil
    var jsonResult: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
    if (jsonResult != nil) {
        if let image_id_array : NSArray! = jsonResult?.valueForKey("Result")?.valueForKey("id") as? NSArray {
            self.id_array = image_id_array   
        }
        if let description_Array = jsonResult?.valueForKey("Result")?.valueForKey("description") as? NSArray {
            self.description_array = description_Array
        }
        if let img_array = jsonResult?.valueForKey("Result")?.valueForKey("image") as? NSArray {
            self.images_array = img_array
        }
    }
}

如何在swift中使用dispatch_async。我想从我的应用程序中的URL加载图像

3 个答案:

答案 0 :(得分:0)

您应该编写代码以从像这样的

这样的网址加载图片
cell.imageView.image = [UIImage imageNamed:@"default_icon"];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
    NSData *data = [NSData dataWithContentsOfURL:imageURL];
    UIImage *image = [UIImage imageWithData:data];
    dispatch_async(dispatch_get_main_queue(), ^{
        cell.imageView.image = image;
    });
});

您应该仅使用主队列进行更改UI,而不是使用下载图像。

答案 1 :(得分:0)

添加下载图像的整个方法,并将其添加到以下框中的数组中:

dispatch_async(dispatch_get_main_queue()) {
     // add you code here
}

答案 2 :(得分:0)

尝试这样做异步请求...

let url = NSURL(string:"http://juzhotel.com/smartcreatives/catholic_app/app/index.php/webservices/getCatholicHighlight")
let request = NSMutableURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
 {
    (response, data, error) in

         if let HTTPResponse = response as? NSHTTPURLResponse {
             let statusCode = HTTPResponse.statusCode
             if statusCode == 200 {
                        // Yes, Do something.
              let resstr = NSString(data: data, encoding: NSUTF8StringEncoding)
               println("Data Reriving %@",resstr)
             }
          }

  }

它在我的代码中工作正常