始终显示UIActivityIndi​​catorView

时间:2017-06-16 00:50:09

标签: ios swift

UIActivityIndicatorView始终显示在我的应用中。

我正在制作 Swift app ,我想在我的应用中创建一个系统,将图像上传到我的 Django服务器。我的目标是在选择图片时制作,然后点按发送按钮,将图片发送到服务器,UIActivityIndicatorView出现并滚动。但现在UIActivityIndicatorView已经显示选择图像。

my app when I run

my app when I select image

import Foundation

import MobileCoreServices

import UIKit

class PhotoController:UIViewController,UINavigationControllerDelegate,UIImagePickerControllerDelegate{    

    @IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!

    @IBOutlet weak var label: UILabel!

    @IBOutlet weak var myImageView: UIImageView!

    private var imagePicker:UIImagePickerController!



    @IBAction func uploadButtonTapped(_ sender: Any) {

        myImageUploadRequest()

    }

    override func viewDidLoad() {

        super.viewDidLoad()

        label.adjustsFontSizeToFitWidth = true

        label.minimumScaleFactor = 0.5

        label.text = "Tap the PhotoSelect or Camera to upload a picture"

     }

    @IBAction func PhotoSelect(_ sender: Any) {

        let myPickerController = UIImagePickerController()

        myPickerController.delegate = self;

        myPickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary

        self.present(myPickerController, animated: true, completion: nil)
    }

    @IBAction func Camera(_ sender: Any) {

        let sourceType:UIImagePickerControllerSourceType = UIImagePickerControllerSourceType.camera

        // カメラが利用可能かチェック

        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){

            // インスタンスの作成

            let cameraPicker = UIImagePickerController()

            cameraPicker.sourceType = sourceType

            cameraPicker.delegate = self

            self.present(cameraPicker, animated: true, completion: nil)



        }

        else{

            label.text = "error"       

        }

    }

    // 撮影が完了時した時に呼ばれる

    func imagePickerController(_ imagePicker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {

            myImageView.contentMode = .scaleAspectFit

            myImageView.image = pickedImage
        }

        //閉じる処理

        imagePicker.dismiss(animated: true, completion: nil)

        label.text = "Tap the Send to save a picture"



    }

    // 撮影がキャンセルされた時に呼ばれる

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {

        picker.dismiss(animated: true, completion: nil)

        label.text = "Canceled"

    }
    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }
    func myImageUploadRequest()

    {
        let myUrl = NSURL(string: "http://localhost:8000/admin/accounts/post/");
        let request = NSMutableURLRequest(url:myUrl! as URL);

        request.httpMethod = "POST";

        //ユーザーごとに割り振りたい

        let param = [

            "firstName"  : "Sergey",

            "lastName"    : "Kargopolov",

            "userId"    : "9"

        ]
        let boundary = generateBoundaryString()
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
        guard let myImage = myImageView.image else {

            return

        }

        let imageData = UIImageJPEGRepresentation(myImageView.image!, 1)
        if(imageData==nil)  { return; }
        request.httpBody = createBodyWithParameters(parameters: param, filePathKey: "file", imageDataKey: imageData! as NSData, boundary: boundary) as Data

        myActivityIndicator.startAnimating();



        let task = URLSession.shared.dataTask(with: request as URLRequest) {

            data, response, error in



            if error != nil {

                print("error=\(error)")

                return

            }

            // You can print out response object

            print("******* response = \(response)")
            // Print out reponse body

            let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)

            print("****** response data = \(responseString!)")
            do {

                let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
                DispatchQueue.main.async {

                    self.myActivityIndicator.stopAnimating()

                    self.myImageView.image = nil;

                }
            }catch

            {

                print(error)

            }     

        }

        task.resume()

    }

    func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {

        let body = NSMutableData();
        if parameters != nil {

            for (key, value) in parameters! {

                body.appendString(string: "--\(boundary)\r\n")

                body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")

                body.appendString(string: "\(value)\r\n")

            }

        }
        let filename = "user-profile.jpg"
        let mimetype = "image/jpg"
        body.appendString(string: "--\(boundary)\r\n")

        body.appendString(string: "Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")

        body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
        body.append(imageDataKey as Data)
        body.appendString(string: "\r\n")
        body.appendString(string: "--\(boundary)--\r\n")
        return body
    }

    func generateBoundaryString() -> String {

        return "Boundary-\(NSUUID().uuidString)"
    }
}

extension NSMutableData {
    func appendString(string: String) {

        let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)

        append(data!)

    }

}

我真的不明白为什么会这样,我在我的代码中写道

myActivityIndicator.startAnimating();

self.myActivityIndicator.stopAnimating()

为什么UIActivityIndicatorView始终显示?我怎样才能制作出理想的应用程序?我应该添加一些代码?

3 个答案:

答案 0 :(得分:0)

您忘记在viewDidLoad()中添加此属性:

myActivityIndicator.hidesWhenStopped = true

您也可以在故事板中的Attributes Inspector / Activity Indicator View部分进行设置。

希望这可以提供帮助: - ))

答案 1 :(得分:0)

除非您设置activityIndicator属性,否则hidesWhenStopped始终可见。

  

要在动画停止时自动隐藏活动指示,请进行设置   hidesWhenStopped属性为true。

您可以在viewDidLoad功能或故事板中设置此值。

myActivityIndicator.hidesWhenStopped = true

因此,无论何时拨打myActivityIndicator.stopAnimating = true,都会触发hidesWhenStopped

答案 2 :(得分:0)

您必须将UIActivityIndicatorView的属性设置为hidesWhenStopped true

您可以通过编程方式或storyboard

设置属性

解决方案1:

enter image description here

解决方案2:

viewdidload中添加此行,

myActivityIndicator.hidesWhenStopped = true