我在我的应用程序中创建了一个活动指示器:
@IBAction func LocateMe(sender: AnyObject) {
Loading.hidden = false
Loading.startAnimating()
}
隐藏了ViewDidLoad,当我点击LocateMe按钮时,我想开始在屏幕上看到它加载。 问题是它开始加载但很晚,它在应用程序打开下一个视图控制器时启动。 您有任何想法,一旦用户点击按钮,我怎么能开始在屏幕上显示它。如果用户等待并且没有指示器向他显示操作已完成,则它是无用的。我也是开放的例子。
import UIKit
import MapKit
import CoreLocation
import SwiftyJSON
import SVProgressHUD
struct City {
let name : String
let location : CLLocation
let description :String
let imageName : NSURL
let fileLink : NSURL
func distanceTo(location:CLLocation) -> Int
{
let distanceMeters = location.distanceFromLocation(self.location)
let distanceKilometers = distanceMeters / 1000.00
return Int(round(100 * distanceKilometers) / 100)
}
}
class FirstViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var Loading: UIActivityIndicatorView!
@IBOutlet weak var LocateMeButton: UIButton!
@IBOutlet weak var LabelTest: UILabel!
@IBOutlet weak var Slider: UISlider!
@IBOutlet weak var LabelValueSlider: UILabel!
var MySliderCurrentValue = Double()
var locationManager = CLLocationManager()
var userLoc : CLLocation!
var cities = [City]()
var nearbyCities = [City]()
override func viewDidLoad() {
super.viewDidLoad()
Loading.hidden = true
LocateMeButton.layer.cornerRadius = 5
// Do any additional setup after loading the view, typically from a nib.
// let path: String = NSBundle.mainBundle().pathForResource("cities", ofType: "json") as String!
let path = NSData(contentsOfURL: NSURL(string: "http://www.99website.eu/citiescopy.json")!) as NSData!
// let jsonData = NSData(contentsOfFile: path) as NSData!
var error : NSError?
let ReadableJSON2 = JSON ( data:path, options: NSJSONReadingOptions.MutableContainers, error: &error )
print(error)
do {
let jsonObject = try NSJSONSerialization.JSONObjectWithData(path!, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]
for city in jsonObject["cities"] as! [[String:AnyObject]] {
//let coordinates = position["Position"] as! [String:CLLocationDegrees]
let cityName = city["Name"] as! String
let latitude = city["Latitude"] as! Double
let longitude = city["Longitude"] as! Double
let description = city["Description"] as! String
let image = city["Image"] as! String
let lin = city["Link"] as! String
let location = CLLocation(latitude: latitude, longitude: longitude)
let city = City(name: cityName, location: location,description: description, imageName: NSURL( string: image )!, fileLink: NSURL( string: lin )! )
cities.append(city)
}
} catch let error as NSError {
print(error)
}
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.requestWhenInUseAuthorization()
locationManager.startMonitoringSignificantLocationChanges()
locationManager.startUpdatingLocation()
if locationManager.respondsToSelector(#selector(locationManager.requestWhenInUseAuthorization)) {
locationManager.requestWhenInUseAuthorization()
locationManager.requestLocation()
}
else {
locationManager.startUpdatingLocation()
}
}
答案 0 :(得分:0)
我认为你的问题是@AsadAli所说的。您在主线程上同步加载数据。您应该尝试将其移动到后台线程(异步),这样您的UI就不会被阻止。
你可以这样做:
/**
Loads the JSON data asyncrounously
- parameter urlString: the URL
- parameter completion: call on the main thread when the transaction is complete. Returning the data if it's there and an error if one exist.
*/
func loadJSONAsync(urlString: String, completion:(data: NSData?, error: NSError?) ->()) {
NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: urlString)!, completionHandler: { (data, response, error) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if error != nil {
completion(data: nil, error: error)
}
else {
completion(data: data, error: nil)
}
})
}).resume()
}
然后在viewDidLoad
:
loadJSONAsync("") { (data, error) in
if let err = error {
print(err)
}
else {
//process JSON data
}
}
只是为了快速清理你的viewDidLoad
我会像这样构建它:
override func viewDidLoad() {
super.viewDidLoad()
Loading.hidden = true
LocateMeButton.layer.cornerRadius = 5
//
// You should start showing a loading wheel heree
//
//Load the JSON
loadJSONAsync("http://www.99website.eu/citiescopy.json") { (data, error) in
if let err = error {
print(err)
}
else {
processJSON(data)
}
}
// Start your location manager
startLocationManager()
}
func processJSON(data: NSData) {
var error : NSError?
let ReadableJSON2 = JSON ( data:path, options: NSJSONReadingOptions.MutableContainers, error: &error )
print(error)
do {
let jsonObject = try NSJSONSerialization.JSONObjectWithData(path!, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]
for city in jsonObject["cities"] as! [[String:AnyObject]] {
//let coordinates = position["Position"] as! [String:CLLocationDegrees]
let cityName = city["Name"] as! String
let latitude = city["Latitude"] as! Double
let longitude = city["Longitude"] as! Double
let description = city["Description"] as! String
let image = city["Image"] as! String
let lin = city["Link"] as! String
let location = CLLocation(latitude: latitude, longitude: longitude)
let city = City(name: cityName, location: location,description: description, imageName: NSURL( string: image )!, fileLink: NSURL( string: lin )! )
cities.append(city)
//
// You should stop showing a loading wheel heree
//
}
} catch let error as NSError {
print(error)
}
}
func startLocationManager() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.requestWhenInUseAuthorization()
locationManager.startMonitoringSignificantLocationChanges()
locationManager.startUpdatingLocation()
if locationManager.respondsToSelector(#selector(locationManager.requestWhenInUseAuthorization)) {
locationManager.requestWhenInUseAuthorization()
locationManager.requestLocation()
}
else {
locationManager.startUpdatingLocation()
}
}
/**
Loads the JSON data asyncrounously
- parameter urlString: the URL
- parameter completion: call on the main thread when the transaction is complete. Returning the data if it's there and an error if one exist.
*/
func loadJSONAsync(urlString: String, completion:(data: NSData?, error: NSError?) ->()) {
NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: urlString)!, completionHandler: { (data, response, error) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if error != nil {
completion(data: nil, error: error)
}
else {
completion(data: data, error: nil)
}
})
}).resume()
}
...你的变量名也应该用小写声明:)