从url获取时,数据不会附加到全局变量中

时间:2016-09-01 07:33:51

标签: ios swift nsstring

我需要你的帮助。我从url获取数据并想要在tableview中显示。但是当我下载数据时。数据被正确获取但是当相同的数据存储在全局变量中时,数组字符串类型然后显示将... 我的代码是

    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 请帮帮我!!!

1 个答案:

答案 0 :(得分:0)

以下是您的问题研究的示例。你想做这样的事情吗?

  

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
    }
}
}
  

Main.storyboard

<?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>