简体   繁体   中英

ios swift app extension to share image

I'm trying to follow 2.2 from Vandad Nahavandipoor's book iOS 8 Swift Programming Cookbook O'REILLY Nov, 2014 first edition.

I understand and have corrected some bugs in the text already, but this one has me stumped.

I'm trying to create a share extension for my app so that people can upload images to my site.

The extension works in that it appears in the last and when you click it, it gives you a place to put the title and shows the image, however, the POST is not active but disabled. I'm new to iOS so I am not sure quite what to do.

In the section he goes on to add an audience selector which I skipped, I have a feeling that might be part of it, but I don't have that option so I didn't put it in.

Here is the code for my share extension

import UIKit
import Social
import MobileCoreServices


class ShareViewController: SLComposeServiceViewController, NSURLSessionDelegate {

var imageData: NSData?

override func isContentValid() -> Bool {    
    if let data = imageData {
        if countElements(contentText) > 0 {
            return true
        }
    }
    return false
}

override func presentationAnimationDidFinish() {
    super.presentationAnimationDidFinish()
    placeholder = "Title"

    let content = extensionContext!.inputItems[0] as NSExtensionItem
    let contentType = kUTTypeImage as NSString

    for attachment in content.attachments as [NSItemProvider]{
        if attachment.hasItemConformingToTypeIdentifier(contentType){
            let dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
            dispatch_async(dispatchQueue, {[weak self] in
                let strongSelf = self!
                attachment.loadItemForTypeIdentifier(contentType, options: nil, completionHandler: {(content: NSSecureCoding!, error: NSError!) in
                    if let data = content as? NSData {
                        dispatch_async(dispatch_get_main_queue(), {
                            strongSelf.imageData = data
                            strongSelf.validateContent()
                        })
                    }
                })
            })
        }
        break
    }
}

override func didSelectPost() {
    //TODO if no FBSession - then don't do it
    let token = FBSession.activeSession().accessTokenData.accessToken

    let identifier = NSBundle.mainBundle().bundleIdentifier! + "." + NSUUID().UUIDString
    let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(identifier)

    let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
    let url = NSURL(string: "http://...&text="+self.contentText)

    let request = NSMutableURLRequest(URL: url!)
    request.HTTPMethod = "POST"
    request.HTTPBody = imageData!

    let task = session.uploadTaskWithRequest(request, fromData: request.HTTPBody)

    task.resume()

    extensionContext!.completeRequestReturningItems([], completionHandler: nil)

}

// override func configurationItems() -> [AnyObject]! {
    // To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.
//    return NSArray()
//}

}

I just want to enable the POST action in the share popup. thanks in advance

EDIT

continuing on, I've discovered the issue is that the imageData of the selected image is nil. content holds the value

file:///var/mobile/Media/DCIM/100APPLE/IMG_0001.JPG

at the line

if let data = content as? NSData{ ...}

fails. how do I read in this image as NSData?

The solution is

image = UIImage(data: NSData(contentsOfURL: content as NSURL)!)

thanks to

Unable to cast UIImage in swift iOS 8 Extension

您将要使用NSData.dataWithContentsOfFile(content)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM