簡體   English   中英

從網址獲取數據時,數據未追加到全局變量中

[英]Data is not append in global variable while getting from url

我需要你的幫助。 我正在從url獲取數據,並希望顯示在tableview中。 但是當我下載數據時。 數據已正確提取,但是當相同數據存儲在全局變量go array字符串類型中時,它將顯示將..我的代碼是

    let requestURL: NSURL = NSURL(string: "https://api.myjson.com/bins/260yg")!
    let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(urlRequest) {
        (data, response, error) -> Void in
         //print(NSString(data:data!,encoding:NSUTF8StringEncoding))
        do{
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
          if  let users = json["userid"] as? NSArray

            {
                for(var i = 0; i < users.count; i++)
                {
                    if let userindex = users[i] as? NSDictionary
                    {
                       if let username =  userindex ["name"] as? NSString
                        {

                           self.tablename.append(username as String)
                            print(self.tablename)
                      if let email = userindex ["email"] as? NSString
                        {
                           self.tableemail.append(email as String)

                        }
                    }
                }
            }
}
            else
            {
                print("nil")
            }
            }
        catch
        {
            print("Error with Json: \(error)")
        }
        }

    task.resume()

全局變量名是tablename和tableemail,請幫助我!

這是研究您的問題的示例。 你想做這樣的事情嗎?

ViewController.swift

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet var tableView: UITableView!
var dataIsLoading = true
var usersArray = [User]()

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self

    let requestURL: NSURL = NSURL(string: "https://api.myjson.com/bins/260yg")!
    let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(urlRequest) {
        (data, response, error) -> Void in
        //print(NSString(data:data!,encoding:NSUTF8StringEncoding))
        do{
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
            if  let users = json["userid"] as? NSArray {
                for user in  users {
                    if let usersDictionary = user as? NSDictionary{
                        let newUser = User(jsonData: usersDictionary)
                        self.usersArray.append(newUser)
                        print(newUser.description)
                    }
                }
                dispatch_async(dispatch_get_main_queue()) {
                    self.dataIsLoading = false
                    self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: .Right)

                }
            }
            else {
                print("nil")
            }
        }
        catch {
            print("Error with Json: \(error)")
        }
    }

    task.resume()
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if dataIsLoading {
        return 1
    }

    return usersArray.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    if dataIsLoading {
        if let cell = tableView.dequeueReusableCellWithIdentifier("CellWithActivityIndicator") {
            return cell
        }
    } else {
        if let cell = tableView.dequeueReusableCellWithIdentifier("Cell") {

            if let userName = usersArray[indexPath.row].name {
                cell.textLabel!.text = userName
            }

            if let userEmail = usersArray[indexPath.row].email {
                cell.detailTextLabel?.text = userEmail
            }

            return cell
        }
    }
    return UITableViewCell()
}
}

User.swift

import Foundation

class User {

var email: String?
var id: String?
var legalName: String?
var name: String?
var originalEmail: String?
var status: String?

init (jsonData: NSDictionary) {

    // NSLog("\(jsonData)")

    if let value = jsonData["email"] as? String{
        self.email =  value
    }

    email = getStringFromDictionary(jsonData, key: "email")
    id = getStringFromDictionary(jsonData, key: "id")
    legalName = getStringFromDictionary(jsonData, key: "legalName")
    name = getStringFromDictionary(jsonData, key: "name")
    originalEmail = getStringFromDictionary(jsonData, key: "originalEmail")
    status = getStringFromDictionary(jsonData, key: "status")
}

private func getStringFromDictionary(jsonData: NSDictionary, key: String) -> String? {
    if let value = jsonData[key] as? String {
        return value
    } else {
        return nil
    }
}

var description: String {
    get {
        var _description = ""

        if let email = self.email {
            _description += "email:             \(email)\n"
        }

        if let id = self.id {
            _description += "id:                \(id)\n"
        }

        if let legalName = self.legalName {
            _description += "legalName:         \(legalName)\n"
        }

        if let name = self.name {
            _description += "name:              \(name)\n"
        }

        if let originalEmail = self.originalEmail {
            _description += "originalEmail:     \(originalEmail)\n"
        }

        if let status = self.status {
            _description += "status:            \(status)\n"
        }

        return _description
    }
}
}

主板

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10117" systemVersion="15G31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="BYZ-38-t0r">
<dependencies>
    <deployment identifier="iOS"/>
    <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>
</dependencies>
<scenes>
    <!--View Controller-->
    <scene sceneID="tne-QT-ifu">
        <objects>
            <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="stackoverflow_39265393" customModuleProvider="target" sceneMemberID="viewController">
                <layoutGuides>
                    <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
                    <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
                </layoutGuides>
                <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
                    <rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
                    <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                    <subviews>
                        <tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" translatesAutoresizingMaskIntoConstraints="NO" id="wiD-eI-g2J">
                            <rect key="frame" x="0.0" y="28" width="600" height="572"/>
                            <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
                            <prototypes>
                                <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" reuseIdentifier="Cell" textLabel="Cmd-qa-ocs" detailTextLabel="HrM-h8-4qX" style="IBUITableViewCellStyleSubtitle" id="JkC-WR-0Eh">
                                    <rect key="frame" x="0.0" y="28" width="600" height="44"/>
                                    <autoresizingMask key="autoresizingMask"/>
                                    <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="JkC-WR-0Eh" id="hFF-W8-2zx">
                                        <rect key="frame" x="0.0" y="0.0" width="600" height="43"/>
                                        <autoresizingMask key="autoresizingMask"/>
                                        <subviews>
                                            <label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="Cmd-qa-ocs">
                                                <rect key="frame" x="15" y="5" width="32" height="20"/>
                                                <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
                                                <fontDescription key="fontDescription" type="system" pointSize="16"/>
                                                <color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
                                                <nil key="highlightedColor"/>
                                            </label>
                                            <label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Subtitle" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="HrM-h8-4qX">
                                                <rect key="frame" x="15" y="25" width="41" height="14"/>
                                                <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
                                                <fontDescription key="fontDescription" type="system" pointSize="11"/>
                                                <color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
                                                <nil key="highlightedColor"/>
                                            </label>
                                        </subviews>
                                    </tableViewCellContentView>
                                </tableViewCell>
                                <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" reuseIdentifier="CellWithActivityIndicator" id="yH2-KE-eBt">
                                    <rect key="frame" x="0.0" y="72" width="600" height="44"/>
                                    <autoresizingMask key="autoresizingMask"/>
                                    <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="yH2-KE-eBt" id="EfS-TK-7UW">
                                        <rect key="frame" x="0.0" y="0.0" width="600" height="43"/>
                                        <autoresizingMask key="autoresizingMask"/>
                                        <subviews>
                                            <activityIndicatorView opaque="NO" contentMode="scaleToFill" horizontalHuggingPriority="750" verticalHuggingPriority="750" animating="YES" style="gray" translatesAutoresizingMaskIntoConstraints="NO" id="0B4-ch-yMB">
                                                <rect key="frame" x="290" y="12" width="20" height="20"/>
                                                <color key="color" red="0.57687498029999995" green="0.69275407970000002" blue="1" alpha="1" colorSpace="calibratedRGB"/>
                                            </activityIndicatorView>
                                        </subviews>
                                        <constraints>
                                            <constraint firstItem="0B4-ch-yMB" firstAttribute="centerY" secondItem="EfS-TK-7UW" secondAttribute="centerY" id="90S-0E-56m"/>
                                            <constraint firstItem="0B4-ch-yMB" firstAttribute="centerX" secondItem="EfS-TK-7UW" secondAttribute="centerX" id="nZM-Fl-Kcf"/>
                                        </constraints>
                                    </tableViewCellContentView>
                                </tableViewCell>
                            </prototypes>
                        </tableView>
                    </subviews>
                    <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
                    <constraints>
                        <constraint firstItem="wiD-eI-g2J" firstAttribute="bottom" secondItem="wfy-db-euE" secondAttribute="top" id="Ab4-X2-fLx"/>
                        <constraint firstItem="wiD-eI-g2J" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leading" id="DX3-Yd-a76"/>
                        <constraint firstItem="wiD-eI-g2J" firstAttribute="top" secondItem="y3c-jy-aDJ" secondAttribute="bottom" constant="8" symbolic="YES" id="Sbi-vj-app"/>
                        <constraint firstAttribute="trailing" secondItem="wiD-eI-g2J" secondAttribute="trailing" id="jtQ-Jz-Crb"/>
                    </constraints>
                </view>
                <connections>
                    <outlet property="tableView" destination="wiD-eI-g2J" id="ev1-pJ-OzP"/>
                </connections>
            </viewController>
            <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
        </objects>
        <point key="canvasLocation" x="664" y="467"/>
    </scene>
</scenes>
</document>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM