使用Swift 2,我有以下代码:
//
// CheckInternet.swift
//
// Created by Dincer on 14/11/15.
//
import AFNetworking
public class Reachability {
private static let theSharedInstance:Reachability = Reachability();
private var isClientOnline:Bool = true;
private var isClientWiFi:Bool = false;
private var isClientConnectionUnknown = false;
func onOnline() {
print("****************************************** Network goes online.");
}
func onOffline() {
print("****************************************** Network goes offline.");
}
func onWiFi() {
print("****************************************** Wifi network on");
}
func onGSM() {
print("****************************************** GSM network on");
}
func onUnknownConnectionStatus() {
print("****************************************** Unkown network status");
}
func isConnectedToNetwork() -> Bool {
return isClientOnline;
}
func isConnectedToWiFi() -> Bool {
return isClientOnline && isClientWiFi;
}
static func sharedInstance() -> Reachability {
return Reachability.theSharedInstance;
}
static func registerListener() {
sharedInstance().registerListener();
}
func registerListener() {
AFNetworkReachabilityManager.sharedManager().setReachabilityStatusChangeBlock { (status: AFNetworkReachabilityStatus) -> Void in
switch status {
case .NotReachable:
self.isClientConnectionUnknown = false;
if self.isClientOnline {
self.isClientOnline = false;
self.onOffline();
}
case .ReachableViaWiFi:
self.isClientConnectionUnknown = false;
if !self.isClientOnline {
self.isClientOnline = true;
self.onOnline();
}
if !self.isClientWiFi {
self.isClientWiFi = true;
self.onWiFi();
}
case .ReachableViaWWAN:
self.isClientConnectionUnknown = false;
if !self.isClientOnline {
self.isClientOnline = true;
self.onOnline();
}
if self.isClientWiFi {
self.isClientWiFi = false;
self.onGSM();
}
case .Unknown:
if !self.isClientConnectionUnknown {
self.isClientConnectionUnknown = true;
self.onUnknownConnectionStatus();
}
}
}
AFNetworkReachabilityManager.sharedManager().startMonitoring();
}
}
不幸的是,这没有用。
有什么帮助才能让它发挥作用?
答案 0 :(得分:1)
我相信用SwiftyJSON
来获取一个JSON
对象到swift中你应该做的数组类型
datas["products"].array or datas["products"].arrayValue
您是否首先将数组类扩展为shuffle方法?如果没有,你可以做这样的事情
extension CollectionType {
/// Return a copy of `self` with its elements shuffled
func shuffle() -> [Generator.Element] {
var list = Array(self)
list.shuffleInPlace()
return list
}
}
extension MutableCollectionType where Index == Int {
/// Shuffle the elements of `self` in-place.
mutating func shuffleInPlace() {
// empty and single-element collections don't shuffle
guard count >= 2 else { return }
for i in 0..<count - 1 {
let j = Int(arc4random_uniform(UInt32(count - i))) + i
guard i != j else { continue }
swap(&self[i], &self[j])
}
}
}
Source 。差异:
If
语句已更改为guard
。
然后你可以做这样的事情
let shuffled = (datas["products"].array!).shuffle()
或者,如果您可以使用iOS 9 API,则无需任何扩展即可执行以下操作:
let shuffled = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(datas["products"].array!)