124課:上傳發布圖片

課程筆記文集地址:Udemy課程:The Complete iOS 9 Developer Course - Build 18 Apps

Section 8 主要的內容是克隆 Instagram:107 - 128課。

一、布局 Storyboard

1.添加 Post 按鈕

如上圖所示,在用戶列表里添加 Post 按鈕(ItemBarButton),點擊 Post 跳轉到下圖中的界面(segue類型選擇 Show):


2.創建上傳圖片的界面

如上圖,在 Storyboard 中拖拽控制器和相應的控件。

控件:UIImageView、UIButton * 2、UITextField。

3.設置 AutoLayout 約束

4.新建 PostImageViewController.swift

創建此界面對應的類文件:PostImageViewController.swift,到 Storyboard 中進行關聯。

5.創建 Action 和 Outlet 連接

@IBOutlet var imageToPost: UIImageView!
@IBOutlet var message: UITextField!
@IBAction func chooseImage(sender: AnyObject) {

}

@IBAction func postImage(sender: AnyObject) {

}

二、實現選擇圖片按鈕功能(Choose An Image)

1. 協議

class PostImageViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

}

2.彈出圖片選擇器

    @IBAction func chooseImage(sender: AnyObject) {        
        let image = UIImagePickerController()
        image.delegate = self
        image.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        image.allowsEditing = false
        
        self.presentViewController(image, animated: true, completion: nil)
        
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        self.dismissViewControllerAnimated(true, completion:nil)
        imageToPost.image = image
        
    }

三、實現發布圖片按鈕功能(Post Image)

1. 在 LeanCloud 創建存儲對象

@IBAction func postImage(sender: AnyObject) {
    let post = AVObject(className: "Post")
    post.setObject(message.text, forKey: "message")
    post.setObject(AVUser.currentUser()!.objectId!, forKey: "userId")
}

2.使用 AVFile

    let imageData = UIImagePNGRepresentation(imageToPost.image!)
    let imageFile = AVFile(name: "image.png", data: imageData!)
    post.setObject(imageFile, forKey: "imageFile")

3.將圖片存儲到 LeanCloud 服務器

    post.saveInBackgroundWithBlock{(success, error) -> Void in
        if error == nil {
              //存儲成功
        } else {
              //存儲失敗
        }
    }

4.在上傳圖片過程中不允許有其他操作
添加一個 ActivityIndicator,在上傳的過程中出現,然后讓用戶等待上傳圖片結束,在沒有結束之前用戶不能進行其他的操作,保存成功后 ActivityIndicator 消失,用戶可以繼續其他操作。

創建變量:

var activityIndicator = UIActivityIndicatorView()

設置屬性:

    activityIndicator = UIActivityIndicatorView(frame: self.view.frame)
    activityIndicator.backgroundColor = UIColor(white: 1.0, alpha: 0.5)
    activityIndicator.center = self.view.center
    activityIndicator.hidesWhenStopped = true
    activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
    view.addSubview(activityIndicator)
    activityIndicator.startAnimating()        
    UIApplication.sharedApplication().beginIgnoringInteractionEvents()

結束旋轉:

self.activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()

5.沒有上傳圖片不能點擊發布
增加提示,檢測用戶是否已經上傳圖片。這里可以將提示框做成帶參數的方法,能夠多次利用此方法。

    func displayAlert(title: String, message: String) {
        
        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction((UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
            
            self.dismissViewControllerAnimated(true, completion: nil)
            
        })))
        
        self.presentViewController(alert, animated: true, completion: nil)
        
    }

判斷條件為在存儲過程中是否有錯誤:

        post.saveInBackgroundWithBlock{(success, error) -> Void in            
            self.activityIndicator.stopAnimating()            
            UIApplication.sharedApplication().endIgnoringInteractionEvents()            
            if error == nil {                
                self.displayAlert("Image Posted!", message: "Your image has been posted successfully")                
            } else {                
                self.displayAlert("Could not post image", message: "Please try again later")                
            }            
        }

7.點擊 Post 方法完整的代碼

@IBAction func postImage(sender: AnyObject) {
    activityIndicator = UIActivityIndicatorView(frame: self.view.frame)
    activityIndicator.backgroundColor = UIColor(white: 1.0, alpha: 0.5)
    activityIndicator.center = self.view.center
    activityIndicator.hidesWhenStopped = true
    activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
    view.addSubview(activityIndicator)
    activityIndicator.startAnimating()        
    UIApplication.sharedApplication().beginIgnoringInteractionEvents()

    let post = AVObject(className: "Post")
    post.setObject(message.text, forKey: "message")
    post.setObject(AVUser.currentUser()!.objectId!, forKey: "userId")
    let imageData = UIImagePNGRepresentation(imageToPost.image!)
    let imageFile = AVFile(name: "image.png", data: imageData!)
    post.setObject(imageFile, forKey: "imageFile")

    post.saveInBackgroundWithBlock{(success, error) -> Void in
        if error == nil {
              //存儲成功
              self.displayAlert("圖片已發布!", message: "你的圖片已經成功上傳") 
              //存儲成功后將圖片控件里的圖片變成默認圖片
              self.imageToPost.image = UIImage(named: "默認圖片.png")
              //存儲成功后將文本框里的文字清空
              self.message.text = ""
        } else {
              //存儲失敗
              self.displayAlert("無法發布圖片", message: "請再試一下")   
        }
    }
}

四、結束

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,573評論 25 708
  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,257評論 4 61
  • 1.首先應該檢測一下目前電腦上擁有的java的版本: 2.如果已經有java8了,就可以直接跳轉到第四步: 3.沒...
    關瑋琳linSir閱讀 11,657評論 0 24
  • 有一個年齡段,總愛唏噓自己已經變老了,變老可以概括很多狀況, 有時候是認真的,但有時候只是戲謔的。 應該只是想表示...
    2小閱讀 313評論 1 1
  • 如果可以擁有100個胃,我愿意將99個胃,都留給順德。——列車長 1 “食出廣東,廚在鳳城”, 鳳城,正是如今的順...
    公元2046閱讀 546評論 0 0